Trapping
Rain WaterMar
10 '12
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!
对于任意i,决定此列能装多少水的是它左边最大的高度和右边最大的高度。所以,先扫一遍可以得到每个i左边最高的高度值,然后从右向左扫一遍可以得到i右边最高的高度值,这次扫描时可以直接求出i的储水值,所以不再需要存储,直接通过这次扫描可以得到最后的返回值。
代码如下:
class Solution {
public:
int trap(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n <= 2) return 0;
int* left_highest = new int[n];
memset(left_highest,0,sizeof(int)*n);
int left_max = 0;
int right_max = 0;
int sum = 0;
for(int i = 0;i<n;i++)
{
left_highest[i] = left_max;
left_max = max(left_max,A[i]);
}
for(int i = n-1; i >= 0; i--)
{
right_max = max(right_max,A[i]);
sum += max(0,min(left_highest[i],right_max)-A[i]);
}
return sum;
}
};
34 milli secs