美文网首页
单调栈 03

单调栈 03

作者: 眼若繁星丶 | 来源:发表于2021-03-24 12:18 被阅读0次

单调栈 03


LeetCode 456

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

单调栈

  • 需要一个 preMin[n] 来记录 0 ~ i 区间内最小的数,即 132模式的 “1”
  • 需要一个栈 stack 从后向前遍历,去找 “3”
  • 至于那个 “2” 就是在从后向前遍历的过程中,num[i] 充当的角色。找到直接返回。
import java.util.*;

public class Solution {

    public boolean find132pattern(int[] nums) {
        int n = nums.length;
        int[] preMin = new int[n];  // 0 ~ i the smallest num
        preMin[0] = nums[0];
        for (int i = 1; i < n; i++)
            preMin[i] = Math.min(preMin[i - 1], nums[i]);
        // the stack store num bigger than preMin[i] and smaller than num[i]
        Deque<Integer> stack = new LinkedList<Integer>();
        for (int i = n - 1; i >= 0; i--) { // from tail to head traversal update stack
            if (nums[i] > preMin[i]) {
                // peek num smaller than all front of num is illicit
                while (!stack.isEmpty() && stack.peek() <= preMin[i])
                    stack.pop();
                // judge whether find 132 pattern
                if (!stack.isEmpty() && stack.peek() < nums[i]) // 3(peek) < 2(num[i])
                    return true;
                stack.push(nums[i]);    // not find, push the num that smaller than preMin[i] into stack
            }
        }
        return false;
    }

}

相关文章

  • 单调栈 03

    单调栈 03 [https://imgtu.com/i/6bEcND] https://leetcode-cn.c...

  • 单调栈和应用实践

    什么是单调栈 单调栈的定义:单调栈即满足单调性的栈结构。与单调队列相比,其只在一端进行进出。 如何使用单调栈 单调...

  • 1.单调栈

    一、单调栈定义 单调栈(monotone-stack)是指栈内元素(栈底到栈顶)都是(严格)单调递增或者单调递减的...

  • 单调栈 2020-06-12(未经允许,禁止转载)

    1.单调栈 指栈内元素保持单调性的栈结构,分为单调增栈(栈底到栈顶元素递增)和单调减栈(栈底到栈顶元素递减) 2....

  • LeetCode刷题指北----单调栈

    1.什么是单调栈?有什么好处? 定义: 单调栈就是栈内元素递增或者单调递减的栈,并且只能在栈顶操作。单调栈的维护是...

  • C语言之单调栈

    单调栈 What 单调栈也是栈的一种,满足先进后出的原则,另外,单调栈中的元素是有序的,分为两种 单调递增栈:单调...

  • 腾讯笔试--逛街

    主要的知识点是:单调栈,该题牢牢记得:栈中记录当前楼能看到的元素 单调栈是单调递增栈,栈顶是最小值单调栈存的是能看...

  • 题解——单调栈

    单调栈题解 单调栈结构 牛客链接 方法:单调栈 算法 这里维护一个单调递增栈,可以找到比当前元素要小的元约定:当前...

  • 单调栈

    leetcode - 42. 接雨水单调栈即元素严格单调递增或单调递减的栈,只需要在元素入栈的时候保持栈的单调性即...

  • Java版算法模版总结(2)

    本次233酱介绍下单调栈、单调队列、并查集、KMP算法,欢迎交流指正~ 单调栈 「单调栈」首先是一种基于栈的数据结...

网友评论

      本文标题:单调栈 03

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