给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1] 输出: 6
基本思路:
首先找到最高的那个柱子,然后从两边向中间那个最高的柱子进行遍历即可。O(N)时间 ,O(1)空间。
class Solution {
public:
int trap(vector<int>& height) {
int Len=height.size(),Max=0,Index=0,Res=0;
for(int i=0;i<Len;i++){
if(Max<height[i]){
Max=height[i];
Index=i;
}
}
// From Left to Right
int MaxL=0;
for(int i=0;i<Index;i++){
if(height[i]>MaxL){
MaxL=height[i];
}else{
Res+=(MaxL-height[i]);
}
}
// From Right to Left
int MaxR=0;
for(int i=Len-1;i>Index;i--){
if(height[i]>MaxR){
MaxR=height[i];
}else{
Res+=(MaxR-height[i]);
}
}
return Res;
}
};