456. 132 Pattern
Given an array of integers a1, a2, a3…an, judge if there exists the 132 pattern.
132 pattern is ai < ak < aj, in which i < j < k.
Solution:
Find the subsequence s1 < s3 < s2
- Search from the end of the array, the current is the s1 candidate, because this is the first place in the array
- If the current is smaller than the top number in the stack, push it in; If the current is larger than some of the numbers in the stack, pop the smaller ones, let s3 = the last pop, and push the current in. The stack holds the s2 candidates.
- If the current is smaller than the s3, which means it is definitely < all in the stack, which is the s2 candidates, return true.
- If the it doesn’t meet the return true condition, return false.
1 public class Solution { 2 public boolean find132pattern(int[] nums) { 3 int s1, s3 = Integer.MIN_VALUE; 4 Stack<Integer> stack = new Stack<Integer>(); 5 for(int i = nums.length - 1; i >= 0; i--) { 6 if(nums[i] < s3) return true; 7 else { 8 while(!stack.isEmpty() && nums[i] > stack.peek()) { 9 s3 = stack.pop(); 10 } 11 } 12 stack.push(nums[i]); 13 } 14 return false; 15 } 16 }