法一:双指针
class Solution {
public:
int trap(vector<int>& height) {
int sum = 0;
//记录每个位置上左边柱子高度的最大值
int maxLeft[height.size()];
maxLeft[0] = height[0];
for(int i = 1; i < height.size(); i++){
maxLeft[i] = max(height[i], maxLeft[i - 1]);
}
//记录每个位置上右边柱子高度的最大值
int maxright[height.size()];
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]);
}
for(int i = 0; i < height.size(); i++){
if(i == 0 || i == height.size() - 1)
continue;
else{
int h = min(maxLeft[i], maxright[i]) - height[i];
if(h > 0) sum += h;
}
}
return sum;
}
};
法二:单调栈
class Solution {
public:
int trap(vector<int>& height) {
int sum = 0;
stack<int> st;
st.push(0);
for(int i = 1; i < height.size(); i++){
if(height[i] < height[st.top()])
st.push(i);
else if(height[i] == height[st.top()]){
st.pop();
st.push(i);
}
else{
while(!st.empty() && height[i] > height[st.top()]){
int curHeight = height[st.top()];
st.pop();
if(!st.empty()){
int colWidth = i - st.top() - 1;
int colHeight = min(height[i], height[st.top()]) - curHeight;
sum += colHeight * colWidth;
}
}
st.push(i);
}
}
return sum;
}
};