

使用 贪心算法 解决这个问题,只需要维护两个最小值 first
和 second
,如果找到了比 second
还大的数,就说明存在递增的三元组。
代码实现
python
def increasingTriplet(nums):
first = second = float('inf')
for num in nums:
if num <= first:
first = num # 更新最小值
elif num <= second:
second = num # 更新次小值
else:
return True # 找到了 third 使得 first < second < third
return False
# 测试示例
print(increasingTriplet([1, 2, 3, 4, 5])) # 输出: True
print(increasingTriplet([5, 4, 3, 2, 1])) # 输出: False
print(increasingTriplet([2, 1, 5, 0, 4, 6])) # 输出: True
思路解析
- 初始化
first
和second
为正无穷大,表示目前找到的最小和次小元素。 - 遍历数组 :
- 若
num <= first
,更新first
,表示找到了更小的数。 - 若
num <= second
,更新second
,表示找到了更小的次小数。 - 若
num > second
,说明已经找到了third
,满足first < second < third
,返回True
。
- 若
- 如果遍历结束还没返回
True
,则返回False
。
时间 & 空间复杂度
- 时间复杂度:O(n)(遍历一次数组)
- 空间复杂度:O(1)(只用了两个额外变量)
这种方法高效且不需要额外的存储空间,是最优解!