Fork me on GitHub

单调栈

单调栈。

单调栈

判别是否需要使用单调栈,如果需要找到左边或者右边第一个比当前位置的数大或者小,则可以考虑使用单调栈;单调栈的题目如矩形米面积等等

来源739官解评论区

739. 每日温度

stack存数组的下标。

1
Deque<Integer> stack = new LinkedList<Integer>();

思路是while(栈不空&&当前温度大于栈顶温度),计算ans[],栈顶出栈。

1
2
3
4
5
6
7
8
9
10
11
int length = temperatures.length;
Deque<Integer> stack = new LinkedList<Integer>();
int[] ans = new int[length];
for(int i = 0; i < length; i++){
int temperature = temperatures[i];
while(!stack.isEmpty() && temperature > temperatures[stack.peek()]){
int preIndex = stack.pop();
ans[preIndex] = i - preIndex;
}
stack.push(i);
}

496. 下一个更大元素 I 单调栈+哈希

503. 下一个更大元素 II 单调栈+循环数组

42. 接雨水

84. 柱状图中最大的矩形



本文标题:单调栈

文章作者:tsuki

发布时间:2022.08.06 - 22:01

最后更新:2022.08.16 - 16:09

原始链接:https://tsuki419.github.io/单调栈.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------THE END-------------
0%