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.
[img]http://www.leetcode.com/wp-content/uploads/2012/08/rainwatertrap.png[/img]
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!

让我们计算出存水的总量,如果从左边依次计算,计算当前最高点和最低点之间的存水量,这样计算的结果小于实际的存水量,因为当前的最底点可能会被淹没(如果它两边有比它高的,它就会被淹没)。我们可以采用两个指针,从两边开始,找到一个最高点,然后再找到一个次高点,保持最高点不动,只移动次高点,次高点减去移动经过的柱子就是总的存水量。代码如下:

public class Solution {
public int trap(int[] height) {
if(height == null || height.length < 3) return 0;
int left = 0;
int right = height.length - 1;
int secondMaxHeight = Integer.MIN_VALUE;
int area = 0;
while(left < right) {
if(height[left] < height[right]) {
secondMaxHeight = Math.max(secondMaxHeight, height[left]);
area += secondMaxHeight - height[left];
left ++;
} else {
secondMaxHeight = Math.max(secondMaxHeight, height[right]);
area += secondMaxHeight - height[right];
right --;
}
}
return area;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值