力扣算法学习day41-2
42-接雨水
题目


代码实现
class Solution {
public int trap(int[] height) {
LinkedList<Integer> stack = new LinkedList<>();
int result = 0;
stack.push(0);
for(int i = 0;i < height.length;i++){
while(!stack.isEmpty() && height[i] >= height[stack.peek()]){
if(height[i] == height[stack.peek()]){
stack.pop();
break;
}
int mid = stack.pop();
if(stack.isEmpty()){
break;
}
int x = i - stack.peek() - 1;
int y = Math.min(height[i],height[stack.peek()]) - height[mid];
int area = x * y;
result += area;
}
stack.push(i);
}
return result;
}
}
|