LeetCode-42-接雨水

  |   0 评论   |   0 浏览

题目描述:

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

image.png

思路:

image.png

代码:

public int trap(int[] height) {
        int ans = 0, current = 0;
        Deque<Integer> stack = new LinkedList<Integer>();
        while (current < height.length) {
            while (!stack.isEmpty() && height[current] > height[stack.peek()]) {
                int top = stack.pop();
                if (stack.isEmpty()) {
                    break;
                }
                int distance = current - stack.peek() - 1;
                int bounded_height = Math.min(height[current], height[stack.peek()]) - height[top];
                ans += distance * bounded_height;
            }
            // 加到队尾
            // stack.add();
            // 加到队头
            stack.push(current++);
        }
        return ans;
    }

运行结果:

image.png


标题:LeetCode-42-接雨水
作者:guobing
地址:http://www.guobingwei.tech/articles/2020/12/01/1606785094318.html