美文网首页
Leetcode 456 - 132 Pattern

Leetcode 456 - 132 Pattern

作者: BlueSkyBlue | 来源:发表于2018-09-13 10:50 被阅读24次

    题目:

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


    思路:

    该题利用到了这一数据结构。该题求解的是132 Pattern。栈中存储当前最大的数。同时设置一个值third。用于存储132中3位置的数。将给定的数组从后往前遍历,一旦当前数据大于栈中的数据就弹出栈。third存储弹出数据中最大的值。一旦当前遍历到的数据小于third则返回true。此时third记录着3位置的数据,栈中记录着2位置的数据,遍历到的数据为1位置上的数据。


    代码:

    public boolean find132pattern(int[] nums) {
            if(nums == null || nums.length == 0)
                return false;
            boolean result = false;
            int third = Integer.MIN_VALUE;
            Stack<Integer>stack = new Stack<Integer>();
            for(int i=nums.length-1;i>=0;i--){
                if(nums[i] < third)
                    return true;
                while(!stack.isEmpty() && nums[i] > stack.peek()){
                    third = Math.max(third, stack.pop());
                }
                stack.push(nums[i]);
            }
            return result;
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 456 - 132 Pattern

          本文链接:https://www.haomeiwen.com/subject/rbxwgftx.html