Skip to content

Latest commit

 

History

History
157 lines (122 loc) · 3.81 KB

File metadata and controls

157 lines (122 loc) · 3.81 KB

English Version

题目描述

给你一个整数数组 nums ,数组中共有 n 个整数。132 模式的子序列 由三个整数 nums[i]nums[j]nums[k] 组成,并同时满足:i < j < knums[i] < nums[k] < nums[j]

如果 nums 中存在 132 模式的子序列 ,返回 true ;否则,返回 false

 

进阶:很容易想到时间复杂度为 O(n^2) 的解决方案,你可以设计一个时间复杂度为 O(n logn)O(n) 的解决方案吗?

 

示例 1:

输入:nums = [1,2,3,4]
输出:false
解释:序列中不存在 132 模式的子序列。

示例 2:

输入:nums = [3,1,4,2]
输出:true
解释:序列中有 1 个 132 模式的子序列: [1, 4, 2] 。

示例 3:

输入:nums = [-1,3,2,0]
输出:true
解释:序列中有 3 个 132 模式的的子序列:[-1, 3, 2]、[-1, 3, 0] 和 [-1, 2, 0] 。

 

提示:

  • n == nums.length
  • 1 <= n <= 104
  • -109 <= nums[i] <= 109

解法

单调栈实现。

Python3

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        ak = float('-inf')
        stack = []
        for num in nums[::-1]:
            if num < ak:
                return True
            while stack and num > stack[-1]:
                ak = stack.pop()
            stack.append(num)
        return False

Java

class Solution {
    public boolean find132pattern(int[] nums) {
        int ak = Integer.MIN_VALUE;
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = nums.length - 1; i >= 0; --i) {
            if (nums[i] < ak) {
                return true;
            }
            while (!stack.isEmpty() && nums[i] > stack.peek()) {
                ak = stack.pop();
            }
            stack.push(nums[i]);
        }
        return false;
    }
}

TypeScript

function find132pattern(nums: number[]): boolean {
    const n = nums.length;
    if (n < 3) {
        return false;
    }
    let last = -Infinity;
    const stack = [];
    for (let i = n - 1; i >= 0; i--) {
        const num = nums[i];
        if (num < last) {
            return true;
        }
        while (stack[stack.length - 1] < num) {
            last = Math.max(last, stack.pop());
        }
        stack.push(num);
    }
    return false;
}

Rust

impl Solution {
    pub fn find132pattern(nums: Vec<i32>) -> bool {
        let n = nums.len();
        if n < 3 {
            return false;
        }
        let mut last = i32::MIN;
        let mut stack = vec![];
        for i in (0..n).rev() {
            if nums[i] < last {
                return true;
            }
            while !stack.is_empty() && stack.last().unwrap() < &nums[i] {
                last = stack.pop().unwrap();
            }
            stack.push(nums[i])
        }
        false
    }
}

...