LeetCode OJ-42-Trapping Rain Water

来源:互联网 发布:js中获取name属性 编辑:程序博客网 时间:2024/05/17 18:45

题目:

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;    }}
0 0
原创粉丝点击