LeetCode[132] Pattern

Leetcode[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.less

Note: n will be less than 15,000.this

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].

Stack

複雜度
O(N),O(N)code

思路
維護一個pair, 裏面有最大值和最小值。若是當前值小於pair的最小值,那麼就將原來的pair壓進去棧,而後在用這個新的pair的值再進行更新。若是當前值大於pair的最大值,首先這個值和原來在stack裏面的那些pair進行比較,若是這個值比stack裏面的值的max要大,就須要pop掉這個pair。若是沒有適合返回的值,就從新更新當前的pair。input

代碼it

Class Pair {
    int min;
    int max;
    public Pair(int min, int max) {
        this.min = min;
        this.max = max;
    }
}

public boolean find123Pattern(int[] nums) {
    if(nums == null || nums.length < 3) return false;
    Pair cur = new Pair(nums[0], nums[0]);
    Stack<Pair> stack = new Stack<>();
    for(int i = 1; i < nums.length; i ++) {
        if(nums[i] < cur.min) {
            stack.push(cur);
            cur = new Pair(nums[i], nums[i]);
        }
        else if(nums[i] > cur.max) {
            while(!stack.isEmpty() && stack.peek().max <= nums[i]) {
                stack.pop();
            }
            if(!stack.isEmpty() && stack.peek.max > nums[i]) {
                return true;
            }
            cur.max = nums[i];
        }
        else if(nums[i] > cur.min && nums[i] < cur.max) {
            return true;
        }
    }
    return false;
}
相關文章
相關標籤/搜索