File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Given nums, return true if there is a 132 pattern where
3
+ num[i] < nums[k] < nums[j] for i < j < k
4
+
5
+ Use a monotonically decreasing stack to store a pair
6
+ {candidate nums[j], candidate nums[i]} where
7
+ candidate nums[i] is the minimum number in nums before j
8
+
9
+ Traverse nums.
10
+ Pop the stack while n >= candidate nums[j] at the top of the stack (n is a better candidate than those)
11
+ Then, if stack not empty, check if 132 patter if found --> return True
12
+ Else, add the current num as a candidate nums[j] with the current min as the candidate nums[i] then update current min
13
+ */
14
+ class Solution {
15
+ public:
16
+ bool find132pattern (vector<int >& nums) {
17
+ stack<pair<int , int >> s;
18
+ int curMin = nums[0 ];
19
+
20
+ for (auto & n : nums){
21
+ // pop all values in stack that have nums[j] candidate <= n
22
+ while (!s.empty () && s.top ().first <= n){
23
+ s.pop ();
24
+ }
25
+ // if stack not empty, check if we found 132 pattern
26
+ if (!s.empty () && s.top ().second < n) return true ;
27
+ else {
28
+ // add n to stack and update curMin
29
+ s.push ({n, curMin});
30
+ curMin = min (curMin, n);
31
+ }
32
+ }
33
+ return false ;
34
+ }
35
+ };
You can’t perform that action at this time.
0 commit comments