单调栈

每日温度

leetcode题目链接

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

思路草稿

每日温度

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] res = new int[temperatures.length];
Stack<Integer> stack = new Stack<>();
stack.push(0);

for(int i = 1;i<temperatures.length;i++){
if(temperatures[i]<=temperatures[stack.peek()]){
stack.push(i);
} else {
while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){
res[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
}
return res;
}
}

接雨水

leetcode题目链接

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

思路草稿

接雨水

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public int trap(int[] height) {
if(height==null||height.length==0){
return 0;
}

int h = 0;
int w = 0;
int res = 0;

Stack<Integer> stack = new Stack<>();
stack.push(0);

for(int i = 1;i<height.length;i++){
if(height[i]<height[stack.peek()]){
stack.push(i);
} else if(height[i]==height[stack.peek()]){
stack.pop();
stack.push(i);
} else {
while(!stack.isEmpty()&&height[i]>height[stack.peek()]){
int mid = stack.pop();
if(!stack.isEmpty()){
h = Math.min(height[stack.peek()],height[i])-height[mid];
w = i-stack.peek()-1;
res += h*w;
}
}
stack.push(i);
}
}

return res;
}
}

柱状图中最大的矩形

leetcode题目链接

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

思路草稿

柱状图中最大的矩形

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public int largestRectangleArea(int[] heights) {
if(heights==null||heights.length==0){
return 0;
}
int[] newHeights = new int[heights.length+2];
newHeights[0] = 0;
newHeights[newHeights.length-1] = 0;
for(int i = 0;i<heights.length;i++){
newHeights[i+1] = heights[i];
}

Stack<Integer> stack = new Stack();
stack.push(0);

int res = 0;

for(int i = 1;i<newHeights.length;i++){
if(newHeights[i]>newHeights[stack.peek()]){
stack.push(i);
} else if(newHeights[i]==newHeights[stack.peek()]){
stack.pop();
stack.push(i);
} else {
while(!stack.isEmpty()&&newHeights[i]<newHeights[stack.peek()]){
int mid = stack.pop();
if(!stack.isEmpty()){
int left = stack.peek();
int right = i;
int h = newHeights[mid];
int w = right-left-1;
res = Math.max(res,h*w);
}
}
stack.push(i);
}
}
return res;
}
}