LeetCode 42.接雨水

2 阅读1分钟

思路

我们采用单调栈的思路来解决这个问题,我们使用单调栈获取每一个元素最左边和最右边比他大的值,然后还需要获取下标,这样我们可以计算出宽和高,然后计算出能够接雨水的面积,所有的面积加和就是结果。

代码

class Solution {

    public int trap(int[] height) {

        Stack<Integer> stack = new Stack<>();

        int ans = 0;

        for(int i=0;i<height.length;i++){

            while(!stack.isEmpty() && height[i]>height[stack.peek()]){

                int bottom = stack.pop();

                int right = i;

                if(stack.isEmpty()) break;

                int left = stack.peek();

                int h = Math.min(height[left],height[right])-height[bottom];

                int w = right-left-1;

                ans += h*w;

            }

            stack.push(i);

        }

        return ans;

    }

}