-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path456. 132 Pattern.cpp
34 lines (33 loc) · 1.06 KB
/
456. 132 Pattern.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public boolean find132pattern(int[] nums) {
int n = nums.length;
if(n < 3){
return false;
}
int[] mins = new int[n];
// make list of mins at num index
mins[0]=nums[0];
for(int i=1;i<n;i++){
mins[i] = Math.min(mins[i-1],nums[i]);
}
Stack<Integer> stack = new Stack<>(); // keep track of potential k's in decreasing order
for(int i=n-1;i>=0;i--){
if(stack.isEmpty()){
stack.push(nums[i]);
};
while(!stack.isEmpty() && stack.peek() <= mins[i]){ // while potential k is smaller than i
stack.pop();
}
if(stack.isEmpty()){ // no more potential k's
stack.push(nums[i]);
continue;
}
if(stack.peek() >= nums[i]){ // bigger than j
stack.push(nums[i]);
}else if(stack.peek() > mins[i]){ // between i and j
return true;
}
}
return false;
}
}