Skip to content

Commit 90daa3a

Browse files
committed
add prob #456; O(N) in time and O(N) in space;
1 parent f2268ae commit 90daa3a

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Diff for: 456_132_Pattern.cpp

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
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.
3+
4+
Note: n will be less than 15,000.
5+
6+
Example 1:
7+
Input: [1, 2, 3, 4]
8+
9+
Output: False
10+
11+
Explanation: There is no 132 pattern in the sequence.
12+
Example 2:
13+
Input: [3, 1, 4, 2]
14+
15+
Output: True
16+
17+
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
18+
Example 3:
19+
Input: [-1, 3, 2, 0]
20+
21+
Output: True
22+
23+
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
24+
25+
来源:力扣(LeetCode)
26+
链接:https://leetcode-cn.com/problems/132-pattern
27+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
28+
*/
29+
30+
/* O(N) in time and O(N) in space */
31+
#include <vector>
32+
#include <stack>
33+
using namespace std;
34+
35+
class Solution {
36+
public:
37+
bool find132pattern(vector<int>& nums) {
38+
stack<int> s, l;
39+
int cur_min = INT_MAX;
40+
int prev_min = INT_MAX;
41+
42+
for(int i=0; i<(int)nums.size(); ++i){
43+
cur_min = min(cur_min, nums[i]);
44+
while( (!s.empty())&&(s.top()<=nums[i]) ){
45+
s.pop(); l.pop();
46+
}
47+
if(!s.empty()){
48+
if(l.top()<nums[i]) return true;
49+
}
50+
s.push(nums[i]);
51+
l.push(prev_min);
52+
prev_min = cur_min;
53+
}
54+
55+
return false;
56+
}
57+
};

0 commit comments

Comments
 (0)