1 原始题目
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。要求时间复杂度O(n)。
2 思路
找到最高的柱子的位置index,在最高柱子的左侧,从0到index遍历一次,当前柱子的储水量等于其左侧最高柱子的高度减去当前柱子的高度。同理,再从右往index遍历一次。
遍历两次数据,时间复杂度O(n),空间复杂度O(1)。
3 code
class Solution {
public:
int trap(vector<int>& height) {
int len = height.size();
if (len<=2)
return 0;
//找到最高挡板的位置和高度
int highest=0, index=0;
for (int i=0; i<len; ++i){
if (height[i]>highest){
highest = height[i];
index = i;
}
}
//从左到index遍历一次
int sum=0;
int cur_max = 0;
for (int i=0 ;i<index; ++i){
cur_max = max(cur_max, height[i]);
sum += cur_max-height[i];
}
//从右往index遍历一次
cur_max=0;
for (int i=len-1 ;i>index; --i){
cur_max = max(cur_max, height[i]);
sum += cur_max-height[i];
}
return sum;
}
};