题目来源
题目描述
题目解析
本质是问最长递增子序列长度能否超过2而已
一次遍历
因为我们需要求解的长度仅仅为3,所以我们可以直接将这个三元子序列的值记录下来;
使用两个指针m1和m2,初始化为INT_MAX,然后遍历数组:
- 如果m1 >= curr,则令m1 = curr
- 如果m1 < curr && m2 >= curr,则令m2 = curr
一旦m2被更新了,说明一定会有一个数小于m2,也就是我们成功组成了一个长度为2的递增子序列。所以我们一旦遍历到比m2还大的数,我们直接返回ture。
如果我们遇到比m1小的数,还是要更新m1,有可能的话也要更新m2为更小的值,毕竟m2的值越小,能组成长度为3的递增序列的可能性越大
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int m1 = INT32_MAX, m2 =INT32_MAX;
for(auto a : nums){
if(m1 >= a){
m1 = a;
}else if(m2 >= a){
m2 = a;
}else{
return true;
}
}
return false;
}
};
暴力超时
class Solution {
bool process(vector<int>& nums, int idx, std::vector<int>&path){
if(idx == nums.size()){
return path.size() >= 3;
}
bool p1 = process(nums, idx + 1, path);
bool p2 = false;
if(path.empty() || path.back() < nums[idx] ){
path.emplace_back(nums[idx]);
p2 = process(nums, idx + 1, path);
path.pop_back();
}
return p1 || p2;
}
public:
bool increasingTriplet(vector<int>& nums) {
std::vector<int>path;
return process(nums, 0, path);
}
};