public int trap(int[] height) {
if(height==null || height.length==0){
return 0;
}
int res = 0;
Stack<Integer> s = new Stack<>();
int cur = 0;
while(cur < height.length){
while(!s.isEmpty() && height[cur]>height[s.peek()]){
// 取出栈顶元素
int h = height[s.peek()];
s.pop();
// 栈顶已经是最左边的墙,那么不会形成水洼
if(s.isEmpty()){
break;
}
// 否则计算水洼的大小
int min = Math.min(height[s.peek()],height[cur]);
int distance = cur - s.peek() - 1;
res += distance*(min-h);
}
s.push(cur++);
}
return res;
}
双指针
//双指针解法
public int trap(int[] height) {
if(height.length==0){
return 0;
}
int res = 0;
int left=0 , right=height.length-1;
int leftMax=height[left], rightMax=height[right];
while(left<right){
if(height[left]<height[right]){
if(height[left]>=leftMax){
leftMax=height[left];
}else{
res+=(leftMax-height[left]);
}
left++;
}else{
if(height[right]>=rightMax){
rightMax=height[right];
}else{
res+=(rightMax-height[right]);
}
right--;
}
}
return res;
}
题目描述题目代码栈的使用public int trap(int[] height) { if(height==null || height.length==0){ return 0; } int res = 0; Stack<Integer> s = new Stack<>();...