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!
自己一直在想着从左到右,并且用栈的思想去解,但是这样的话分析起来就很麻烦,而且条件很多。 下面是某位高手的解法,非常简洁,而且这种思想根本不需要考虑太多复杂的判断
class Solution {
public:
int trap(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int maxHeight = 0;
vector<int> leftArr(n);
for (int i = 0; i < n; ++i)
{
leftArr[i] = maxHeight;
if (A[i] > maxHeight)
maxHeight = A[i];
}
maxHeight = 0;
vector<int> rightArr(n);
for (int i = n - 1; i >= 0; --i)
{
rightArr[i] = maxHeight;
if (A[i] > maxHeight)
maxHeight = A[i];
}
int water = 0;
for (int i = 0; i < n; ++i)
{
int temp = min(leftArr[i], rightArr[i]) - A[i];
if (temp > 0)
water += temp;
}
return water;
}
};