接雨水

作者: 我知他风雨兼程途径日暮不赏 | 来源:发表于2020-04-04 10:00 被阅读0次

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water

1.题目

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


图1 接雨水

上面是由数组 [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

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

    }
}

2.JAVA解答

首先找到,最高点,求出整个矩形面积,最高点前从0开始递推,减去空面积和柱子面积;最高点后从数组最大索引往前递推,减去空面积和柱子面积,时间复杂度O(N),空间复杂度O(1)。

class Solution {
    public int trap(int[] height) {
        int res =0;
        int maxIndex =0;
        int maxHeight=0;
        for(int i=0;i<height.length;i++){
            if(height[i]>maxHeight){
                maxIndex=i;
                maxHeight=height[i];
            }
        }
        res = maxHeight*height.length;
        res -= maxHeight;
        int tempHeight=0;
        for(int i=0;i<maxIndex;i++){
            if(height[i]>=tempHeight){
                tempHeight=height[i];
            }
            res -= (maxHeight-tempHeight);
            res -= height[i];
        }
        tempHeight=0;
        for(int j=(height.length-1);j>maxIndex;j--){
            if(height[j]>=tempHeight){
                tempHeight=height[j];
            }
            res -= (maxHeight-tempHeight);
            res -= height[j];
        }
        return res;
    }
}

相关文章

  • 接雨水

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

  • 接雨水

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/trap...

  • 接雨水

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

  • 接雨水

    https://leetcode-cn.com/explore/interview/card/bytedance/...

  • 接雨水

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

  • 接雨水

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/trappi...

  • 接雨水

    题目: 题目的理解: 从示例图中可以很好的理解,题目的意思,真的是题目描述越少越难。最直接的思路:(1)为一个高度...

  • 接雨水

    LeetCode第42题 题目描述:给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下...

  • 接雨水

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

  • 算法:接雨水

    问题 Given n non-negative integers representing an elevatio...

网友评论

      本文标题:接雨水

      本文链接:https://www.haomeiwen.com/subject/htsdphtx.html