问题描述: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.
n
will be less than 20,000
.
使用栈的方法解决。这里需要一个栈和一个变量flag,用来指示第三个元素(即132中的2)。这样只要保证栈中的元素都大于flag,同时新来的数字小于flag,那么则符合要求,如果新来的元素大于flag,那么将栈顶元素赋值flag,将新来的该元素压入栈。保证栈内元素都是大于flag的。c++代码如下:
class Solution {
public:
/**
* @param nums a list of n integers
* @return true if there is a 132 pattern or false
*/
bool find132pattern(vector<int>& nums) {
// Write your code here
int length = nums.size();//数组的大小
int flag = INT_MIN;
stack<int> stac;
for(int i = length-1;i>=0;--i){
if(nums[i]<flag){
return true;
}
else{
while(!stac.empty() && nums[i]>stac.top()){
flag = stac.top();
stac.pop();
}
}
stac.push(nums[i]);
}
return false;
}
};