题目描述:
Given a sequence of n integers
,
, …,
, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and
<
<
. 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.
Example 1:
Input: [1, 2, 3, 4]
Output: False
Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: [3, 1, 4, 2]
Output: True
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
解决方案:
标识说明:下面我们用first表示第一个数字,second表示第二个数字,third表示第三个数字(数组里的相对前后顺序),目标是判断是否存在first < third < second这样的subsequence。
会用到栈,栈的作用:由栈底到栈顶递减保存second的值,并且该值 > third。
我们逆序遍历vector里面的每一个元素作为first:
- 如果first < 当前 third 的值, return true, 因为 first < third,同时栈里面的元素大于third;
- 如果first == 当前third的值, 则跳过;
- 否则, 弹出栈顶的元素并赋值给third,直到栈顶元素<= first; 最后将 first 值放入栈中,作为又一个second值。
C++代码:
class Solution {
public:
bool find132pattern(vector<int>& nums) {
int n = nums.size();
if(n<3)
return false;
stack<int> s; // 存放second > third , 并且由栈顶到栈底 递增
int s3= INT_MIN;
for(int i=n-1;i>=0;i--){
if(nums[i]<s3) return true;
if(nums[i]==s3) continue;
while(!s.empty() && nums[i] > s.top()){ //短路运算符
s3 = s.top();
s.pop();
}
if(!s.empty() && s.top()==nums[i]) //可省略
continue;
s.push(nums[i]);
}
return false;
}
};