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.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.


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 Marcosfor contributing this image!


简要题解:

存储下来的水 = maxHeight * arraySize - bar占的空间 - 流失的水

其中,

maxHeight是拥有最高高度的bar的高度;

arraySize就是数组的元素个数;

bar占的空间的值等于所有的bar的高度乘以bar的宽度(width = 1)的和;

我们重点来看流失的水是怎么求的。从左往右遍历所有的bar,同时维护一个当前的最高高度h。对于第i步,如果height[i] > h,则说明,从开始到i,处在空间高度(height[i]-h)的这部分水都会流失。这样直到遍历完整个数组,我们就得到“往左边流出的”流失的水。同理,用类似的方法从右往左遍历所有的bar我们就能求出“往右边流出的”流失的水。最终,流失的水 = “往左边流出的”流失的水 + “往右边流出的”流失的水。


代码:

class Solution {
public:
    int trap(vector<int>& height) {
        int sz = height.size();
        
        if (0 == sz)
            return 0;
        
        int h = height[0], maxHeight = height[0], water = -height[0];

        for (int i = 1; i < sz; i++) {
            water -= height[i];

            if (height[i] > h) {
                water -= (height[i] - h) * (i - 0);
                h = height[i];
                maxHeight = h;
            }
        }

        h = height[sz-1];
        for (int i = sz - 1; i >= 0; i--) {
            if (height[i] > h) {
                water -= (height[i] - h) * (sz - 1 - i);
                h = height[i];
            }
        }

        water += maxHeight * sz;

        return water;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值