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

Trapping Rain Water

2014-08-16 10:13 281 查看
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!
public class Solution {
public int trap(int[] A) {
if(A==null || A.length<=2) return 0;
int left=0,right=A.length-1;
int all=0,block=0,curr=0;
while(left<=right){
int level=Math.min(A[left],A[right]);
if(level>curr){
all+=(level-curr)*(right-left+1);
curr=level;
}
if(A[left]<A[right]){
block+=A[left++];
}
else{
block+=A[right--];
}
}
return all-block;
}
}


One Pass and O(1) space.

class Solution {
public:
int trap(int A[], int n) {
if(n==0) return 0;
int l = 0, r = n-1,block = 0,all = 0,curlevel = 0;
while(l<=r)
{
if(min(A[l],A[r])>curlevel)
{
all += (min(A[l],A[r])-curlevel)*(r-l+1);
curlevel = min(A[l],A[r]);
}
if(A[l]<A[r])
block += A[l++];
else
block += A[r--];
}
return all-block;
}
};


One Pass and O(1) space.

The idea is search the array from two sides to middle, keep tracking the second highest value and use it to minus the value of A[i] the answer is the capacity of current point.

public class Solution {
public int trap(int[] A) {
int secHight = 0;
int left = 0;
int right = A.length - 1;
int area = 0;
while (left < right) {
if (A[left] < A[right]) {
secHight = Math.max(A[left], secHight);
area += secHight - A[left];
left++;
} else {
secHight = Math.max(A[right], secHight);
area += secHight - A[right];
right--;
}
}
return area;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: