单调栈
接雨水
题目链接:https://leetcode.cn/problems/trapping-rain-water/
暴力
针对每一列求出左右最高的列,然后利用其中相对小的那一个进行计算
优化思路:针对每一列求出,中间有重复计算,因此遍历2轮,分别计算左边最高和右边最高,降低复杂度
class Solution {
public int trap(int[] height) {
int[] left = new int[height.length];
int[] right = new int[height.length];
int max = 0;
for (int i = 0;i< height.length;i++){
left[i] = max;
max = Math.max(max,height[i]);
}
max = 0;
for (int i = height.length-1;i>=0;i--){
right[i] = max;
max = Math.max(max,height[i]);
}
int count = 0;
for (int i = 0;i< height.length;i++){
int h = Math.min(left[i],right[i] );
if (h>height[i]) count+= h-height[i];
}
return count;
}
}
单调栈
按行计算
class Solution {
public int trap(int[] height) {
Deque<Integer> d = new LinkedList<>();
int count = 0;
for (int i = 0;i< height.length;i++){
while(!d.isEmpty()&&height[d.getLast()]<height[i]){
int index = d.removeLast();
if (d.isEmpty()){
continue;
}else {
int left = d.getLast();
int h = Math.min(height[left],height[i] )-height[index];
count += h*(i-left-1);
}
}
while(!d.isEmpty()&&height[d.getLast()]==height[i]){
d.removeLast();
}
d.addLast(i);
}
return count;
}
}
最大的矩形
题目连接:https://leetcode.cn/problems/largest-rectangle-in-histogram
递增栈
class Solution {
public int largestRectangleArea(int[] heights) {
int [] newHeights = new int[heights.length + 2];
newHeights[0] = 0;
newHeights[newHeights.length - 1] = 0;
for (int index = 0; index < heights.length; index++){
newHeights[index + 1] = heights[index];
}
Deque<Integer> d = new LinkedList<>();
int max = 0;
for (int i = 0;i< newHeights.length;i++){
while (!d.isEmpty()&&newHeights[d.getLast()]> newHeights[i]){
int index = d.removeLast();
int len = i - d.getLast()-1;
max = Math.max(max,len*newHeights[index]);
}
d.addLast(i);
}
return max;
}
}