42.接雨水
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 42. 接雨水
* 执行用时:2 ms,
* 内存消耗:38.3 MB,
*/
class Solution {
public int trap(int[] height) {
ArrayDeque<Integer> stack = new ArrayDeque<>();
int sum=0;
for (int current=0;current<height.length;current++){
while (!stack.isEmpty()&&height[current]>=height[stack.peek()]){
Integer pop = stack.pop();
if (stack.isEmpty())break;
int distance=current-stack.peek()-1;
int min=Math.min(height[stack.peek()],height[current]);
int area=(min-height[pop])*distance;
sum+=area;
}
stack.push(current);
}
return sum;
}
}