接到雨水的面积 = 总面积 - 柱子的面积 - 左边没有水的面积 - 右边没有水的面积
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
if(n == 0) return 0;
int res = 0;
int max_height = *max_element(height.begin(), height.end());
//用来保存没有水的case, 两个栈包含的元素都是单调不增的
stack<int> left, right;
//保存左边没有水的面积
for(int i = 0; i < n; i++) {
if(height[i] == max_height) break;
if(left.empty()) left.push(max_height - height[i]);
else {
left.push(min(left.top(), max_height - height[i]));
}
}
//保存右边没有水的面积
for(int i = n-1; i >= 0; i--) {
if(height[i] == max_height) break;
if(right.empty()) right.push(max_height - height[i]);
else {
right.push(min(right.top(), max_height - height[i]));
}
}
//总面积
int total = max_height * n;
//柱子的面积
int pillar = 0;
for(auto i : height)
pillar += i;
//没有水的面积
int left_no_water = 0, right_no_water = 0;
while(!left.empty()) {
left_no_water += left.top();
left.pop();
}
while(!right.empty()) {
right_no_water += right.top();
right.pop();
}
res = total - pillar - left_no_water - right_no_water;
return res;
}
};