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!
思路是这样的:
我们每次只考虑一单位宽度的位置能放多少水。对于某个位置来说,我们先找到它左边的最高点(有可能就是它本身),再找到它右边的最高点(有可能是它本身),然后,这个单位上最多能放min(leftMax, rightMax) - A[i],及两边最大值的较小值减去它的高度,道理由上图显而易见。
class Solution {
public:
int trap(int A[], int n) {
int * lmax = new int[n];
int * rmax = new int[n];
for (int i = 0, Max = -1; i < n; i++) lmax[i] = Max = max(A[i], Max);
for (int i = n - 1, Max = -1; i >= 0; i--) rmax[i] = Max = max(A[i], Max);
int ans = 0;
for (int i = 0; i < n; i++) ans += min(lmax[i], rmax[i]) - A[i];
delete []lmax;
delete []rmax;
return ans;
}
};
后来看到了常数空间复杂度的办法,思路是一样的:
class Solution {
public:
int trap(int A[], int n) {
int a=0;
int b=n-1;
int Max=0;
int leftmax=0;
int rightmax=0;
while(a<=b){
leftmax=max(leftmax,A[a]);
rightmax=max(rightmax,A[b]);
if(leftmax<rightmax){
Max+=(leftmax-A[a]);
a++;
}
else{
Max+=(rightmax-A[b]);
b--;
}
}
return Max;
}
};