0456. 132 Pattern (M)

132 Pattern (M)

题目

Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

Return true if there is a 132 pattern in nums, otherwise, return false.

Follow up: The O(n^2) is trivial, could you come up with the O(n logn) or the O(n) solution?

Example 1:

Input: nums = [1,2,3,4]
Output: false
Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: nums = [3,1,4,2]
Output: true
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: nums = [-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]. 

Constraints:

  • n == nums.length
  • 1 <= n <= 10^4
  • -10^9 <= nums[i] <= 10^9

题意

判断能否在数组中找到3个数nums[i], nums[j], nums[k],满足出i<j<k且nums[i]<nums[k]<nums[j]。

思路

官方解答[LeetCode] 132 Pattern 132模式


代码实现

Java

class Solution {
    public boolean find132pattern(int[] nums) {
        Deque<Integer> stack = new ArrayDeque<>();
        int md = Integer.MIN_VALUE;

        for (int i = nums.length - 1; i >= 0; i--) {
            if (nums[i] < md) {
                return true;
            }
            while (!stack.isEmpty() && nums[i] > stack.peek()) {
                md = stack.pop();
            }
            stack.push(nums[i]);
        }

        return false;
    }
}
posted @ 2020-10-24 11:05  墨云黑  阅读(68)  评论(0编辑  收藏  举报