解:
辅助图片:
class Solution {
public:
int trap(vector<int>& height) {
int value=0;
int cnt = height.capacity();
int maxIndex = 0;
int sum = 0;
//when input = []
if(cnt==0) {
return 0;
}
for(int i=0; i<cnt; i++) {
sum += height[i];
if(height[maxIndex] < height[i]) {
maxIndex = i;
}
}
int higher = height[0];
int extra = height[maxIndex]-height[0];
for(int i=1; i<maxIndex; i++) {
if(height[i]>=higher) {
higher = height[i];
extra += height[maxIndex]-height[i];
}
else {
extra += height[maxIndex]-higher;
}
}
extra += height[maxIndex]-height[cnt-1];
higher = height[cnt-1];
for(int i=cnt-2; i>maxIndex;i--) {
if(height[i]>=higher) {
higher = height[i];
extra += height[maxIndex]-height[i];
}
else {
extra += height[maxIndex]-higher;
}
}
value = height[maxIndex]*cnt - sum - extra;
return value;
}
};