456. 132 Pattern
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.
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].
Example 3:
Input: [-1, 3, 2, 0] Output: True Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
题意:判断一个数组num中是否存在132顺序的三个数,注意2比1大哦。
思路1:
用一个数组mi记录前缀最小值,从后往前遍历,当前为i,用一个set记录i之后出现(已经遍历过)的数,则如果在set中找到在(mi[i-1],num[i])之间的数就存在。复杂度O(n*lgn)
代码:
class Solution_456 {
public:
bool find132pattern(vector<int>& nums) {
int n=nums.size();
if(n<=2) return false;
vector<int>mi(n);
mi[0]=nums[0];
for (int i = 1; i <n ; ++i) {
mi[i]=min(mi[i-1],nums[i]);
}
set<int>ri;
set<int>::iterator it;
ri.insert(nums[n-1]);
for (int i = n-2; i >0 ; --i) {
if(nums[i]>mi[i-1]) {
it=ri.upper_bound(mi[i-1]);
if(it!=ri.end()&&*it<nums[i]) return true;
}
ri.insert(nums[i]);
}
return false;
}
};
思路2:来源于点击打开链接
从后往前遍历,用一个单调递增的栈(栈顶到栈底递增)维护32,2要尽可能大,如果当前数小于2,那么就找到了,否则更新栈。比当前数小的出栈更新2,然后将当前数入栈,复杂度O(n)
代码:
class Solution_456_On {
public:
bool find132pattern(vector<int>& nums) {
int n=nums.size();
if(n<=2) return false;
int two=INT32_MIN;
stack<int>s;
for (int i = n-1; i >=0 ; --i) {
if(nums[i]<two) return true;
while(!s.empty()&&nums[i]>s.top()){
two=s.top();
s.pop();
}
if(s.empty()||s.top()>nums[i]) s.push(nums[i]);
}
return false;
}
};