456. 132 Pattern

Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.

Note: n will be less than 15,000.

Example 1:

Input: [1, 2, 3, 4]

Output: False

Explanation: There is no 132 pattern in the sequence.

 

Example 2:

Input: [3, 1, 4, 2]

Output: True

Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

 

Example 3:

Input: [-1, 3, 2, 0]

Output: True

Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
class Solution {
    public boolean find132pattern(int[] nums) {
        int n = nums.length;
        if(n < 3) return false;
        for(int i = 0; i < n - 2; i++) {
            for(int j = i + 1; j < n - 1; j++) {
                for(int k = j + 1; k < n; k++) {
                    if(nums[i] < nums[k] && nums[k] < nums[j]) return true;
                }
            }
        }
        return false;
    }
}

TLE

class Solution {
    public boolean find132pattern(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        int secondMax = Integer.MIN_VALUE;
        
        for (int i = nums.length - 1; i >= 0; i--) {            
            while (!stack.isEmpty() && stack.peek() < nums[i]) {
                secondMax = stack.pop(); // because max will be nums[i] now.
            }
            if (nums[i] > secondMax) stack.push(nums[i]); // this can be candidate for secondMax
            if (nums[i] < secondMax) return true; // as we found number less than second Max.
        }
        return false;
    }
}

stack的巧用,因为要132,所以不妨从右往左,这样就能先把可能的32push进去,然后用1来比较。stack维护了firstmax最大数。

如果cur 《 第二大的数就返回true,所以第二大的数seconmax很重要,先初始化为最小值,如果peek小于cur,说明最大的数应该是cur了,那么secondmax就是pop。而如果peek 》cur了,说明cur至少小于peek啊,有戏,再看看是不是小于secondmax就好了,如果比secondmax大,说明还不够格,push进去成为了firstmax。如果恰好小于secondmax,说明出现了132pattern。玄乎

posted @ 2020-08-16 13:21  Schwifty  阅读(105)  评论(0编辑  收藏  举报