📅  最后修改于: 2023-12-03 14:51:31.850000             🧑  作者: Mango
在数列中找到大小为3的排序子序列,要求时间复杂度为O(n),空间复杂度为O(1)。
我们需要用到两个变量,smallest
和second_smallest
。我们遍历整个数列,同时判断当前遍历到的数字是否小于等于smallest
,如果小于等于smallest
,则将smallest
更新为该数字;否则,判断当前遍历到的数字是否小于等于second_smallest
,如果小于等于second_smallest
,则将second_smallest
更新为该数字;否则,说明找到了一个大小为3的排序子序列。
def find_sorted_subsequence(nums: List[int]) -> bool:
smallest = float('inf')
second_smallest = float('inf')
for num in nums:
if num <= smallest:
smallest = num
elif num <= second_smallest:
second_smallest = num
else:
return True
return False
这个问题看似简单,但是却有一些注意点。需要注意初始值的设定,以及判断条件的细节。通过这个问题,我们可以带领程序员思考如何在时间和空间复杂度上做到最优解。