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!
这道题也是道经典题,方法是从左向右扫,求每个 index 的左边的 max;然后从右向左扫,求每个 index 的右边的 max。然后求两者之间的 min,减去自身的 value。
其实扫两遍就 okay 了,这里为了代码更为直观,所以还是扫三遍。
class Solution {
public:
int trap(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==0) return 0;
vector<int> leftMax(n,0);
vector<int> rightMax(n,0);
leftMax[0] = A[0];
rightMax[n-1] = A[n-1];
int sum = 0;
for(int i=1;i<n;i++)
{
leftMax[i] = max(leftMax[i-1],A[i]);
}
for(int i=n-2;i>=0;i--)
{
rightMax[i] = max(rightMax[i+1],A[i]);
}
for(int i=0;i<n;i++)
{
sum += min(leftMax[i],rightMax[i]) - A[i];
}
return sum;
}
};
本文介绍了一个经典的编程问题——如何计算给定地形图中能够留存多少雨水。通过两次扫描获得每个位置左右最高点的方法来解决该问题,并给出详细的实现步骤。
378

被折叠的 条评论
为什么被折叠?



