• 单调栈-456. 132模式


    2020-05-05 22:02:37

    问题描述:

    给定一个整数序列:a1, a2, ..., an,一个132模式的子序列 ai, aj, ak 被定义为:当 i < j < k 时,ai < ak < aj。设计一个算法,当给定有 n 个数字的序列时,验证这个序列中是否含有132模式的子序列。

    注意:n 的值小于15000。

    示例1:

    输入: [1, 2, 3, 4]

    输出: False

    解释: 序列中不存在132模式的子序列。
    示例 2:

    输入: [3, 1, 4, 2]

    输出: True

    解释: 序列中有 1 个132模式的子序列: [1, 4, 2].
    示例 3:

    输入: [-1, 3, 2, 0]

    输出: True

    解释: 序列中有 3 个132模式的的子序列: [-1, 3, 2], [-1, 3, 0] 和 [-1, 2, 0].

    问题求解:

    递减单调栈可以得到右侧第一个比当前元素大的元素,只需要再记录一下之前出栈的最大值,只需要其比当前元素大,那么就存在132模式。

    时间复杂度:O(n)

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

      

  • 相关阅读:
    latex之插入伪代码 [转]
    BIBTeX制作参考文献 [转]
    latex 页眉设置 [转]
    python : list tuple set dictionary [转]
    ctags使用简介 [转]
    conda在指定目录下创建虚拟环境
    Ubuntu系统安装Anaconda3
    ModuleNotFoundError: No module named 'google' 问题解决方案
    PyCharm无法输入中文
    checkpoint文件
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/12833153.html
Copyright © 2020-2023  润新知