zoukankan      html  css  js  c++  java
  • 132模式

    2018-09-27 23:20:20

    问题描述:

    问题求解:

    本题的难度还是有的,主要的考虑方向是尽量构造[min, max]来将后面出现的数字插入到其中。这里的求解方法是使用Stack来维护一组non-overlapping的区间,每次判断当前的数字能够加入到区间之中,如果可以,那么就直接返回true,如果不可以,那么就需要维护这个区间栈。这里有个地方需要注意到的是在栈顶的元素的左边界是到当前的为止的最小值,换句话说,Stack中的区间是按照左边界进行排序的。

        public boolean find132pattern(int[] nums) {
            Stack<int[]> stack = new Stack<>();
            for (int i = 0; i < nums.length; i++) {
                if (stack.isEmpty() || stack.peek()[0] > nums[i]) stack.push(new int[]{nums[i], nums[i]});
                // 这里不能直接写else目的是为了过滤掉和当前min相等的数字
                else if (stack.peek()[0] < nums[i]) {
                    if (stack.peek()[1] > nums[i]) return true;
                    else {
                        int[] last = stack.pop();
                        System.out.println(last[0] + " " + last[1]);
                        if (last[1] > nums[i]) return true;
                        last[1] = nums[i];
                        while (!stack.isEmpty() && stack.peek()[1] <= nums[i]) stack.pop();
                        if (!stack.isEmpty() && stack.peek()[0] < nums[i]) return true;
                        stack.push(last);
                    }
                }
            }
            return false;
        }
    
  • 相关阅读:
    Node项目
    Angular模块/服务/MVVM
    Angular介绍1
    Node环境配置及Gulp工具
    Linux及Git介绍
    数据库MySQL
    ReactiveCocoa 监听枚举类型enumerate 或者 NSInteger类型
    ReactiveCocoa 监听布尔(BOOL)类型改变
    python3.7 urlopen请求HTTPS警告'CERTIFICATE_VERIFY_FAILED'解决办法
    Centos yum命令
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/9716287.html
Copyright © 2011-2022 走看看