42-Trapping-Rain-Water
Last updated
Last updated
LinkedList<Integer> stack=new LinkedList<>();
for(int i=0;i<height.length;i++){
while(!stack.isEmpty() && height[stack.peekLast()]<=height[i]){
int curIndex=stack.pollLast();
int base=height[curIndex];
int leftHeight=base;
int left=curIndex;
if(!stack.isEmpty()){
leftHeight=height[stack.peekLast()];
left=stack.peekLast();
}
result+=(Math.min(leftHeight,height[i])-base)*(i-left-1);
}
stack.offer(i);
}
return result;
}---
``` java "找规律"
class Solution {
public int trap(int[] height) {
if(height==null || height.length==0){
return 0;
}
int result=0;
int maxHeight=0;
for(int i=0;i<height.length;i++){
if(height[maxHeight]<height[i]){
maxHeight=i;
}
}
int left=height[0];
for(int i=1;i<maxHeight;i++){
if(left<height[i]){
left=height[i];
}else{
result+=left-height[i];
}
}
int right=height[height.length-1];
for(int i=height.length-2;i>maxHeight;i--){
if(right<height[i]){
right=height[i];
}else{
result+=right-height[i];
}
}
return result;
}
}