[leetcode] 42. Trapping Rain Water

Description

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
trap rain water
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

Input:

[0,1,0,2,1,0,1,3,2,1,2,1]

Output:

6

分析

题目的意思是:给你一个柱形图,然后往里面注水,问柱形图能够装得下多大面积的水。

  • 索引i从左到右,索引j从右往左,遍历的时候寻找左右两边的最大值,如果左边的最大值小于右边的最大值,左边进行操作;如果左边的最大值大于等于右边的最大值,右边进行操作。直到i>j时终止。

C++实现

class Solution {
public:
    int trap(vector<int>& height) {
        int i=0;
        int j=height.size()-1;
        int sum=0;
        int left_max=0;
        int right_max=0;
        while(i<j){
            left_max=max(left_max,height[i]);
            right_max=max(right_max,height[j]);
            if(left_max<right_max){
                sum+=(left_max-height[i]);
                i++;
            }else{
                sum+=(right_max-height[j]);
                j--;
            }
        }
        return sum;
    }
};

Python实现

下面是一个动态规划的实现:对于数组height 中的每个元素,分别向左和向右扫描并记录左边和右边的最大高度,然后计算每个下标位置能接的雨水量。

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0

        n = len(height)
        left_max = [height[0]]+[0]*(n-1)
        for i in range(1,n):
            left_max[i]=max(left_max[i-1], height[i])
        right_max = [0]*(n-1)+[height[n-1]]
        for i in range(n-2,-1,-1):
            right_max[i]=max(right_max[i+1], height[i])
        ans = 0
        for i in range(n):
            ans+=min(left_max[i],right_max[i])-height[i]
        return ans

参考文献

42. Trapping Rain Water

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值