1. 解析
题目大意,判断数组是否存在子序列[a, b, c](不一定连续),使其 a < c < b
2. 分析
刚开始我以为是Increasing Triplet Subsequence,实际上还是有一点小差别的。这里判断的是a < c < b,不是a < b < c,思路有点类似。参考了@Grandyang的博客,他用了单调栈进行求解,即栈中始终保持 b > c,而我们所要做的就是,在保证b > c的基础上,尽可能使c达到最大值,这样a的取值范围可以最大。我们只要检测到存在c > a,即表明数组存在132pattern。
例如 [3, 1, 4, 2]
检测2,s = [2]
检测4,s = [4] c = 2 , 栈中会始终保持 c < b
检测1,返回true
class Solution {
public:
bool find132pattern(vector<int>& nums){
int third = INT_MIN;
stack<int> s;
for (int i = nums.size() - 1; i >= 0; --i){
if (third > nums[i]) return true;
while (!s.empty() && nums[i] > s.top()){
third = s.top();
s.pop();
}
s.push(nums[i]);
}
return false;
}
};
定位法求解:
这类题最经典的莫过于3Sum,思路大同小异。即固定住其中两个位置,移动其中的一个位置,即可判断长度为3的序列。
class Solution {
public:
bool find132pattern(vector<int>& nums){
int first = INT_MAX, n = nums.size();
for (int i = 0; i < n; ++i){
first = min(first, nums[i]); //确定a和b
if (first == nums[i]) continue;
for (int j = n - 1; j > i; --j){ //移动c
if (first < nums[j] && nums[j] < nums[i])
return true;
}
}
return false;
}
};