LeetCode 题解工作台
递增的三元子序列
给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。 如果存在这样的三元组下标 (i, j, k) 且满足 i ,使得 nums[i] ,返回 true ;否则,返回 false 。 示例 1: 输入: nums = [1,2,3,4,5] 输出: true 解释: 任何 …
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
class Solution: def increasingTriplet(self, nums: List[int]) -> bool:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。
如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回 true ;否则,返回 false 。
示例 1:
输入:nums = [1,2,3,4,5] 输出:true 解释:任何 i < j < k 的三元组都满足题意
示例 2:
输入:nums = [5,4,3,2,1] 输出:false 解释:不存在满足题意的三元组
示例 3:
输入:nums = [2,1,5,0,4,6] 输出:true 解释:其中一个满足题意的三元组是 (1, 4, 5),因为 nums[1] == 1 < nums[4] == 4 < nums[5] == 6
提示:
1 <= nums.length <= 5 * 105-231 <= nums[i] <= 231 - 1
进阶:你能实现时间复杂度为 O(n) ,空间复杂度为 O(1) 的解决方案吗?
解题思路
方法一
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
mi, mid = inf, inf
for num in nums:
if num > mid:
return True
if num <= mi:
mi = num
else:
mid = num
return False
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because the array is traversed once. Space complexity is O(1) as only two variables are maintained regardless of input size. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Are you maintaining only essential state variables instead of generating all subsequences?
- question_mark
Can you justify why tracking first and second numbers guarantees correctness?
- question_mark
How would your solution behave on strictly decreasing arrays or repeated elements?
常见陷阱
外企场景- error
Attempting to store all subsequences, leading to O(n^3) time complexity.
- error
Failing to update the second variable correctly when encountering smaller numbers than second but larger than first.
- error
Returning false too early without fully validating all candidates in one pass.
进阶变体
外企场景- arrow_right_alt
Increasing Quadruplet Subsequence: extend tracking to three variables to detect four-element increasing sequences.
- arrow_right_alt
Longest Increasing Subsequence Length ≥ k: generalize invariant tracking to maintain k-1 variables for arbitrary length sequences.
- arrow_right_alt
Strictly Decreasing Triplet: apply similar logic but track maximal decreasing values instead of minimal increasing ones.