leetcode 42.接雨水 Java

做题博客链接

https://blog.csdn.net/qq_43349112/article/details/108542248

题目链接

https://leetcode-cn.com/problems/trapping-rain-water/

描述

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

提示:

n == height.length
0 <= n <= 3 * 104
0 <= height[i] <= 105

示例

示例 1:

在这里插入图片描述

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水
(蓝色部分表示雨水)。 

示例 2:

输入:height = [4,2,0,3,2,5]
输出:9

初始代码模板

class Solution {
    
    
    public int trap(int[] height) {
    
    
      
    }
}

代码

推荐题解,里面除了单调栈之外还有其他优秀的解答方法:
https://leetcode-cn.com/problems/trapping-rain-water/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-8/

class Solution {
    
    
    public int trap(int[] height) {
    
    
        LinkedList<Integer> stack = new LinkedList<>();
        int res = 0;

        for (int i = 0; i < height.length; i ++) {
    
    
            while (!stack.isEmpty() && height[stack.peek()] < height[i]) {
    
    
                int h = height[stack.pop()];
                if (stack.isEmpty()) {
    
    
                    continue;
                }
                h = Math.min(height[stack.peek()], height[i]) - h;
                int w = i - stack.peek() - 1;
                res += h * w;
            }

            stack.push(i);
        }

        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43349112/article/details/114004958
今日推荐