[LeetCode] Trapping Rain Water 搜集雨水

相关问题:一个int数组, 比如 array[],里面数据无任何限制,要求求出 所有这样的数array[i],其左边的数都小于等于它,右边的数都大于等于它。能否只用一个额外数组和少量其它空间实现

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

思路:这个数组中每个位置上能保存的雨水量,取决于该位置左边的数组元素最大值max_1,和该位置右边的数组元素最大值max_2,如果max_1>current element而且max_2>current element,那么该位置上能保存的雨水就是 min(max_1, max_2) - current element。

代码如下:

    int trap(int A[], int n) {
        
        if(n==0 || n==1 || n==2)
            return 0;
            
        int water = 0; // amount of water to be held
        
        int* B = new int[n-2];  // max values for each current element from left to right
        int* C = new int[n-2];  // max values for each current element from right to left
        int max_1 = A[0], max_2 = A[n-1];  // 
        
        for(int i=1; i<n-1; i++)
        {
            B[i-1] = max_1;
            max_1 = max(max_1, A[i]); // update global max
        }
        
        for(int j=n-2; j>0; j--)
        {
            C[n-2-j] = max_2;
            max_2 = max(max_2, A[j]); // update global max
        }
        
        for(int i=0; i<n-2; i++)
        {
            if(B[i]>A[i+1] && C[n-3-i]>A[i+1])
                water = water + min(B[i], C[n-3-i])-A[i+1];
        }
        
        return water;
    }

上面的算法需要从左往右扫描一次,从右往左扫描一次,一共两次。

http://blog.csdn.net/linhuanmars/article/details/20888505给出一个只需扫描一次的算法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值