42. 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.
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!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Solution
C++ Sol1
class Solution {
public:
int trap(vector<int>& A) {
int left = 0, right = A.size()-1;
int res = 0;
int maxleft = 0, maxright = 0;
while(left < right){
if(A[left] <= A[right]){
maxleft = max(maxleft,A[left]);
res += maxleft - A[left];
left++;
}
else{
maxright = max(maxright,A[right]);
res += maxright - A[right];
right--;
}
}
return res;
}
};
C++ Sol2
class Solution {
public:
int trap(vector<int>& v) {
int n = v.size();
if(n == 0) return 0;
vector<int> l(n,v[0]);
vector<int> r(n,v[n-1]);
for(int i = 0; i < n - 1; ++i) {
l[i+1] = max(l[i],v[i+1]);
r[n-i-2] = max(r[n-i-1],v[n-i-2]);
}
int res = 0;
for(int i = 1; i < n-1; ++i) {
res += min(l[i],r[i])-v[i];
}
return res;
}
};
Explanation
双指针:空间复杂度: O ( 1 ) O(1) O(1)
辅助数组:空间复杂度: O ( n ) O(n) O(n)