LeetCode456 132 Pattern

check if an integer array contains 132 pattern.

using the monotonic stack, which is decreasing sequence. and we iterate the array from end position to start position.
the general idea for this problem is to find that “2” “3” pair first, and this will need monotonic stack. and if later, we can find sth that is less than mid point which is 2, then we find the valid triplet! (and don’t forget to iterate the given array in a reversed way!)

class Solution {
    public boolean find132pattern(int[] nums) {
        if(nums == null || nums.length <= 2) return false;
        
        Stack<Integer> stack = new Stack<>();
        int mid = Integer.MIN_VALUE;
        
        for(int i = nums.length - 1; i >= 0; i--) { //we iterate from end
            if(mid > nums[i]) { //and if later we have a left one smaller than mid, then we got "1" which is nums[i], so we find the 132 pattern
                return true;
            } else {
                while (!stack.isEmpty() && stack.peek() < nums[i]) { //stack is an decreasing one
                    mid = stack.pop(); //so mid is the largest but not larger than nums[i],which means less but closest to nums[i]. we set this as mid, and because we push mid eariler than nums[i] and we iterate from last pisition to first position, so in this case, we can assume we find our "2", which is mid, and "3" which is nums[i].
                }
                stack.push(nums[i]);
            }
        }
        return false;
        
    }
} 
posted @ 2020-05-31 12:25  EvanMeetTheWorld  阅读(19)  评论(0)    收藏  举报