LeetCode OJ-42-Trapping Rain Water

题目:

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!

大意:

求数组组成的凹槽能盛水的容积。

思路:

此方法参照:跳出温水的青蛙blog
从两端向中间靠拢,求以两端为边的容器能盛水的容积,然后所有值都减去短边的值,更新数组中元素的值继续向中间靠拢,找到新的两边,不断迭代下去直到中间。
需要注意的是,对于一个元素A[i],其所能盛水的容积可能会比一次while循环中所计入的容积要大,这是由当前两端的边的高度所制约的,不过没有关系,在后面的迭代过程中,会将当前没有计入的容积加上,即每个位置A[i]的容积可能会分多次统计进来。

代码:

public class Solution {
    public int trap(int[] height) {
        if(height.length < 3) return 0;
        //从两端向中间靠拢
        int l = 0;
        int r = height.length - 1;
        int total = 0;

        while(l < r) {
            //高度为0的边作为两边显然不能蓄住水
            if(height[l] == 0) l++;
            if(height[r] == 0) r--;
            //两边中短的边决定容积
            int min = Math.min(height[l], height[r]);
            int temp = 0;
            for(int i = l; i <= r; i++) {
                //碰到比min高的,减掉,为下一次迭代做处理
                if(height[i] >= min)
                    height[i] -= min;
                else {
                    //比min小,计算容积,并置0
                    temp += min - height[i];
                    height[i] = 0;
                }
            }
            total += temp;
        }

        return total;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值