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.

起初用了一个非常笨的方法,在每一个水坑里找到左右两边最高的挡板,然后取最小值,得到体积。复杂度是O(n*n),超时了:

public int trap(int[] height) {
    if(height.length<3)
        return 0;
    int sum=0;
    for (int i = 1; i < height.length-1; i++) {
        int leftIndex=i-1 , rightIndex=i+1;
        int leftMaxHeight=0 , rightMaxHeight=0;
        while(leftIndex>=0){
            if(height[leftIndex]>leftMaxHeight)
                leftMaxHeight=height[leftIndex];
            leftIndex--;
        }
        while(rightIndex<=height.length-1){
            if(height[rightIndex]>rightMaxHeight)
                rightMaxHeight=height[rightIndex];
            rightIndex++;
        }
        if(Integer.min(leftMaxHeight, rightMaxHeight)>height[i])
            sum+=Integer.min(leftMaxHeight, rightMaxHeight)-height[i];
    }
    return sum;
}

后来联想到了前面的Container With Most Water,用两个指针得到了答案,从左右两边选取较小的边往中间靠拢。于是成功了,代码如下:

public int trap(int[] height) {
    if(height.length<3)
        return 0;
    int sum=0;
    int left=0,right=height.length-1;
    //left表示左边最高高度的索引,right表示右边最高高度的索引
    int i=left+1,j=right-1;
    //遍历从1到height.length-2,计算每一个height[i]所盛水的体积
    while(i<=j){
        if(height[left]<=height[right]){
            if(height[i]<height[left]){
                sum+=height[left]-height[i];
            }else{            
                left=i;
            }
            i++;
        }else{
            if(height[j]<height[right]){
                sum+=height[right]-height[j];
            }else{
                right=j;
            }
            j--;
        }
    }
    return sum;
}

关键之处盛水的体积只取决于较短的短板。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值