Given a sequence of n integers a1, a2, …, an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
这道题其实就是不能直接三重循环会超时,我们只需要找到最佳的一组满足条件的132模式,于是,我们先从某个位置开始找到最小的数,再从从最小数的后面开始找到最大数,然后再从最大数的后面开始找到中间大的数,最后得到我们想要的一组132模式的数。这样减少了很多种情况的讨论。
代码如下:
class Solution {
public:
bool find132pattern(vector<int>& nums) {
int n=nums.size();
if(n<3)return false;
int i=0;
int j=0;
int k=0;
while(i<n){
while(i+1<n&&nums[i]>=nums[i+1])i++;
j=i+1;
while(j+1<n&&nums[j]<=nums[j+1])j++;
k=j+1;
while(k<n){
if(nums[k]<nums[j]&&nums[k]>nums[i]){
return true;
}
k++;
}
i=j+1;
}
return false;
}
};