0
点赞
收藏
分享

微信扫一扫

[模板总结] - 单调栈

Aliven888 2022-02-01 阅读 64
数据结构

模板题&链接

Leetcode 907. Sum of Subarray Minimums

Leetcode 901. Online Stock Span

Leetcode 496. Next Greater Element

Leetcode 503. Next Greater Element II

Leetcode 739. Daily Temperatures

Leetcode 239. Sliding Window Maximum

单调栈定义

是指一个栈内保存的元素满足单调递增或者递减的关系

单调栈基本问询功能

  • 求当前元素前一个大于或者小于他的值位置
  • 求当前元素下一个大于或者小于他的值位置

模板代码如下:

int n = arr.length;
 
int[] nextSmall = new int[n];
Arrays.fill(nextSmall, n); // 如果没有下一个更小值那么默认值arr.length
Stack<Integer> stk = new Stack<>();
stk.push(0); // 将第一个元素位置压入栈
 
for(int i=1; i<arr.length; i++) {
    while(!stk.isEmpty() && arr[i]<arr[stk.peek()]) {
        // 如果出现小于栈顶元素,stack pop
        int idx = stk.pop();
        nextSmall[idx] = i;
    }
    stk.push(i);
}

时间复杂度:O(N);空间复杂度:O(N)

举报

相关推荐

0 条评论