美文网首页
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

    题目: Given a sequence of n integers a1, a2, ..., an, a 132...

  • Leetcode 456. 132 Pattern

    文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. S...

  • 456. 132 Pattern

    这道题真的很有意思。我第一遍做的时候很快写了个O(N^2)的solution。后来想到可以做O(NLogN)的解。...

  • 456. 132 Pattern

    看懂题意,得到规律 如果我们找到最大的k,而nums[i]

  • 1-栈

    https://leetcode-cn.com/problems/132-pattern/[https://lee...

  • LeetCode 456: 132模式

    LeetCode 456题 132模式 题目 给定一个整数序列:a1, a2, ..., an,一个132模式的子...

  • [刷题防痴呆] 0456 - 132模式 (132 Patter

    题目地址 https://leetcode.com/problems/132-pattern[https://le...

  • Leetcode: 132-Pattern

    Given a sequence of n integers a1, a2, ..., an,a 132 patt...

  • 132 Pattern

    题目来源给一个数组,判断数组中是否存在132模式的三个元素。我一开始想着n方的方法,就是遍历一遍,然后每次从左找比...

  • 2019-02-09

    LeetCode 290. Word Pattern Description Given a pattern an...

网友评论

      本文标题:Leetcode 456 - 132 Pattern

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