给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 1。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的直方图,在这种情况下,可以接 6 个单位的水(蓝色部分表示水)。 感谢 Marcos 贡献此图。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
解题思路
维护一个单调递减的栈,当遍历到的元素大于栈中元素时,就将栈中的两个元素和当前元素组成一个接雨水的区域
代码
class Solution {public int trap(int[] height) {Stack<Integer> stack=new Stack<>();int n=height.length,res=0;for(int i=0;i<n;i++){while (!stack.isEmpty()&&height[i]>height[stack.peek()]){int top=stack.pop();if(stack.isEmpty())break;int l=stack.peek();int weight=i-l-1;int h=Math.min(height[l],height[i])-height[top];res+=h*weight;}stack.push(i);}return res;}
}