您的位置:首页 > 移动开发

【Leetcode】Rain trapping

2015-08-25 22:18 633 查看
【题目】

 Given n non-negative integers representing anelevation map where the width of each bar is 1, compute how much water it isable to trap after raining.

For example, 

Given 
[0,1,0,2,1,0,1,3,2,1,2,1]
,return 
6
.

【思路】

Note: The following idea is in fact from the last answer in this
link, which leads to a clean code. I just reorganize it and add some explanations. I hope it is Ok.

link:

Here is my idea: instead of calculating area by height*width, we can think it in a cumulative way. In other words, sum water amount
of each bin(width=1). Search from left to right and maintain a max height of left and right separately, which is like a one-side wall of partial container. Fix the higher one and flow water from the lower part. For example, if current height of left is lower,
we fill water in the left bin. Until left meets right, we filled the whole container.

class Solution {
public:
int trap(int A[], int n) {
int left=0; int right=n-1;
int res=0;
int maxleft=0, maxright=0;
while(left<=right){
if(A[left]<=A[right]){
if(A[left]>=maxleft) maxleft=A[left];
else res+=maxleft-A[left];
left++;
}
else{
if(A[right]>=maxright) maxright= A[right];
else res+=maxright-A[right];
right--;
}
}
return res;
}
};


The basic idea is that we set two pointers 
l
 and 
r
 to
the left and right end of 
height
. Then we get the minimum height (
minHeight
)
of these pointers (similar to Container with Most Water due to the Leaking Bucket Effect) since the level of the water cannot be higher than it. Then we move the two pointers towards the center. If the coming level is less than 
minHeight
,
then it will hold some water. Fill the water until we meet some "barrier" (with height larger than 
minHeight
)
and update 
l
 and 
r
to
repeat this process in a new interval.

【代码】

public class Solution {
public int trap(int[] height) {
int n = height.length, l = 0, r = n - 1, water = 0, minHeight = 0;
while (l < r) {
while (l < r && height[l] <= minHeight)
water += minHeight - height[l++];
while (r > l && height[r] <= minHeight)
water += minHeight - height[r--];
minHeight = Math.min(height[l], height[r]);
}
return water;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode