题目链接:https://leetcode-cn.com/problems/trapping-rain-water/
题目如下:
class Solution {
public:
int trap(vector<int>& height) {
//从列看来计算
//关键点1:当前列雨水面积=[min(左边max,右边max)-当前height]*列宽
//关键点2:第一个柱子和最后一个柱子不接雨水
if(height.size()<=2) return 0;
vector<int> maxLeft(height.size(),0);
vector<int> maxRight(height.size(),0);
//记录每个柱子左边柱子的最大高度
maxLeft[0]=height[0];
for(int i=1;i<height.size();i++){
maxLeft[i]=max(height[i],maxLeft[i-1]);
}
//记录每个柱子右边柱子的最大高度
maxRight[height.size()-1]=height[height.size()-1];
for(int i=height.size()-2;i>=0;i--){
maxRight[i]=max(height[i],maxRight[i+1]);
}
//面积求和
int result=0;
for(int i=0;i<height.size();i++){
int size=(min(maxLeft[i],maxRight[i])-height[i])*1;
if(size>=0) result+=size;
}
return result;
}
};