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!
Subscribe to see which companies asked this question
分析:
这个题目看得懂别人的解法,却不能证明正确性。
分别维护左右两边的标记l,r,每次去a[l]与a[r]中的小者,假设a[l]<a[r],对l的左边延伸,若l的右边小于a[l],则用a[l]去减就是装水的地方。一直延伸到l的右边某个点大于左边,停止。反之亦然。
我觉得需要注意的是,最外层的while判断条件,是等于也没关系,因为里面还会保证相等也不会有影响。
代码:
class Solution {
public:
int trap(vector<int>& A) {
int l=0,r=A.size()-1,res=0;
while(l<r)
{
int minn=min(A[l],A[r]);
if(minn==A[l])
{
while(++l<r&&A[l]<=minn)
res+=minn-A[l];
}
else
{
while(l<--r&&A[r]<=minn)
res+=minn-A[r];
}
}
return res;
}
};