456. 132 Pattern!
class Solution {
public boolean find132pattern(int[] nums) {
// O(n) solution: use array and right part of the array as stack
// record the min number from index [0, j]
int[] memo1 = new int[nums.length];
memo1[0] = nums[0];
for (int i=1; i<memo1.length; i++){
memo1[i]=Math.min(memo1[i-1], nums[i]);
}
// use the right part of the memo1 as stack
// for j>=stackTop and j<nums.length-1,
// memo[j]<=memo[j+1]
for (int j = nums.length-1, stackTop = nums.length; j>0; j--){
while(stackTop<nums.length && memo1[stackTop]<=memo1[j]){
stackTop++;
}
if(nums[j]>memo1[j] && stackTop<nums.length && memo1[stackTop]<nums[j])
return true;
if(nums[j]>memo1[j]) memo1[--stackTop]=nums[j];
}
return false;
}
}Last updated
Was this helpful?