题目描述
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
双指针。一开始left指向第一个柱子,right指向最后一个柱子。left_max记录从左到右最高的柱子高度,right_max记录从右到左最高的柱子高度。每一次比较left和right指向的柱子高度,选取短的那一个(因为接水量由短边决定),然后和left_max(如果left短)或right_max(如果right短)比较,如果此时的柱子比记录的最高高度大,则更新最高高度;否则累加此时柱子的接水量,即left_max-height[left]或者right_max-height[right]。(此时left_max<height[right]或者right_max<height[left])
类似的题目:盛最多水的容器
代码(c++)
class Solution {
public:
int trap(vector<int>& height) {
if(height.size()<=1) return 0;
int res=0;
int left=0,right=height.size()-1;
int left_max=0,right_max=0;
while(left<right){
if(height[left]<height[right]){
if(height[left]>left_max) left_max=height[left];
else res+=left_max-height[left];
left+=1;
}
else{
if(height[right]>right_max) right_max=height[right];
else res+=right_max-height[right];
right-=1;
}
}
return res;
}
};