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
这道题我采用的方法是把这个模型看成一层一层的水池,每次计算一层容量。以第一层为例,找到第一层左壁(第一个不为零的数),然后用 l 标记,从 l+1 的位置开始,向右寻找,找到右壁,计算中间的空间,然后右壁变左壁,继续向右寻找。找完第一层,再找第二层,依次到最高层。
代码如下:
class Solution {
public:
int trap(vector<int>& height) {
int highest = 0 ;
int count = 0 ;
for( auto i:height ){
if( i> highest ){
highest = i ;
}
}
for( int i=1;i<=highest;i++ ){
int l = 0 ;
int r ;
for( int j=0;j<height.size();j++ ){
if( height[j]>=i ){
l = j ;
r = l ;
break ;
}
}
for( int j=l+1;j<height.size(); ){
if( height[j]>=i ){
r = j ;
count += (r-l-1) ;
l = r ;
j = l+1 ;
}
else{
j++ ;
}
}
}
return count ;
}
};
在讨论去看到一个高分答案,觉得思路惊奇。先贴代码:
class Solution {
public:
int trap(vector<int>& height) {
int i=0,j=height.size()-1;
int lmax=0, rmax = 0;
int container = 0;
while(i<j){
lmax = height[i] > lmax? height[i]:lmax;
rmax = height[j] > rmax? height[j]:rmax;
if(lmax < rmax){
container += lmax - height[i];
i++;
}else{
container += rmax - height[j];
j--;
}
}
return container;
}
};
他的思路是:
在水池左右两边设立两个标杆,记录左右两边的最高高度,以所给例子为例,一开始左右两边高度为0 ,那么说明左边标杆右边低于一的区域都会有水。标杆每次向中间推进一格,先更新标杆的高度,再判断当前格子中有多少水,用最高高度减去当前格子的高度就可以得到。