42.接雨水
https://leetcode.cn/problems/trapping-rain-water/submissions/
单调栈
class Solution {
public int trap(int[] height) {
Stack<Integer> temp = new Stack<Integer>();
int size = height.length;
if(size <= 2){
return 0;
}
int sum = 0;
temp.push(0);
for(int i=1;i<size;i++){
int StackTop = temp.peek();
if(height[StackTop] > height[i]){
temp.push(i);
}else if(height[StackTop] == height[i]){
temp.pop();
temp.push(i);
}else{
while(!temp.isEmpty()&& height[StackTop] < height[i]){
int mid = temp.pop();
if(!temp.isEmpty()){
int left = temp.peek();
int h = Math.min(height[left],height[i])-height[mid];
int w = i-left-1;
int hold = h * w;
if (hold > 0) sum += hold;
StackTop = temp.peek();
}
}
temp.push(i);
}
}
return sum;
}
}
动态规划:按照列来计算,宽度设为1,求高度差。
雨水面积:min(左边柱子的最高高度,记录右边柱子的最高高度) - 当前柱子高度。
从左向右遍历:maxLeft[i] = Math.max(height[i], maxLeft[i - 1])
从右向左遍历:maxRight[i] = Math.max(height[i], maxRight[i + 1])
时间复杂度为O(n^2)。 空间复杂度为O(1)
class Solution {
public int trap(int[] height) {
int size =height.length;
int sum =0;
int[] leftMax = new int[size];
int[] rightMax = new int[size];
leftMax[0] = height[0];
for(int i=1;i<size;i++){
leftMax[i] = Math.max(leftMax[i-1],height[i]);
}
rightMax[size-1]=height[size-1];
for(int i=size-2;i>=0;i--){
rightMax[i] = Math.max(rightMax[i+1],height[i]);
}
for(int i=0;i<size;i++){
int count = Math.min(leftMax[i],rightMax[i])-height[i];
if(count >0)sum+=count;
}
return sum;
}
}