Coding中等
LC300 最长递增子序列
tails 二分 O(n log n);
简要回答
tails 二分 O(n log n);tails 不是答案序列但长度长度;严格 vs 非严格选。
标准答案
考察点:tails 二分 O(n log n);tails 不是答案序列但长度长度;严格 vs 非严格选。
实现:
import bisectdef length_of_lis(nums):
# tails[k] = 所有长度 k+1 LIS 中末尾的最小值;自然单调递增
tails = []
for x in nums:
# 严格递增用 bisect_left(替换第一个 >= x 的位置)
# 若题目要求非严格递增则用 bisect_right
i = bisect.bisect_left(tails, x)
if i == len(tails):
tails.append(x) # x 比所有尾部都大,扩展长度
else:
tails[i] = x # 否则更新让该长度的尾部更小
常见错误
- 把
tails直接当 LIS 输出(错 - 只长度对)
- 严格/非严格用错
- DP 初值漏 1 致全 0。