原题链接: Leetcode 334.递增的三元子序列
Given an integer array nums
, return true
if there exists a triple of indices (i, j, k)
such that i < j < k
and nums[i] < nums[j] < nums[k]
. If no such indices exists, return false
.
Example 1:
Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.
Example 2:
Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.
Example 3:
Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
- Constraints:
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?
题目大意:
给定一个序列,问其中是否存在递增的三元子序列
贪心做法:
设定一个small和一个mid用来表示目标三元组的前两个数,small初始可设为第一个元素,mid设置为最大。遍历整个序列,有三种情况:
- 如果当前元素小于small,将small更新
- 如果当前元素大于small且小于mid,将mid更新
- 如果当前元素大于mid,说明成功,返回true
时间负责度: O(n),需要遍历一遍数组
空间复杂度: O(n),只用了small和mid两个临时变量
双向遍历做法:
其实满足条件的三元组换一种说法就是:对于中间元素nums[i]来说,他左边元素的最小值比他小,他右边元素的最大值比他大。因此维护两个数组left_min和right_max。left_min[i]表示nums[i]左边元素的最小值,right_max[i]表示nums[i]右边元素的最大值。然后遍历一遍,满足 left_min[i] < nums[i] < right_max[i] 的说明成功,返回true
时间复杂度: O(n),需要遍历数组两次来维护辅助数组,遍历一次进行比较
空间复杂度: O(n),需要两个长度为n的辅助数组
贪心做法:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int n = nums.size();
if (n < 3) return false;
int small = nums[0], mid = INT_MAX;
for (int i = 1; i < n; i++) {
// 加上等号防止出现相等的情况
if(nums[i] <= small) small = nums[i];
else if(nums[i] <= mid) mid = nums[i];
else return true;
}
return false;
}
};
双向遍历做法:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int n = nums.size();
if(n < 3) return false;
// left_min[i]表示nums[i]左边元素中的最小值
vector<int> left_min(n);
left_min[0] = nums[0];
for(int i = 1; i < n; i ++ ){
left_min[i] = min(left_min[i-1], nums[i]);
}
// right_max[i]表示nums[i]右边元素中的最大值
vector<int> right_max(n);
right_max[n-1] = nums[n-1];
for(int i = n - 2; i >= 0; i -- ){
right_max[i] = max(right_max[i+1], nums[i]);
}
for(int i = 1; i < n-1; i ++ ){
if(left_min[i] < nums[i] && nums[i] < right_max[i])
return true;
}
return false;
}
};