https://leetcode-cn.com/problems/trapping-rain-water/
思路:单调栈
int trap(vector<int>& height) {
if (height.size() <= 2) {
return 0;
}
stack<int> st;
int res = 0;
st.push(0);
for (int i = 1; i < height.size(); i++) {
int temp = 0;
//计算栈内面积,temp用于保存2个柱子中间最大值
if (height[i] > height[st.top()]) {
while(!st.empty() && height[st.top()] < height[i]) {
res = res + (min(height[st.top()], height[i]) - temp)* (i - st.top() - 1);
//cout << i << " " << st.top() << " " << temp << " " << (min(height[st.top()], height[i]) - temp)* (i - st.top() - 1) << endl;
temp = max(height[st.top()], temp);
st.pop();
}
}
//计算前面柱子比当前柱子高的第一个柱子面试,例子中:420325中下标0和3之前柱子面积
if (!st.empty()) {
res = res + (min(height[st.top()], height[i]) - temp)* (i - st.top() - 1);
}
st.push(i);
}
return res;
}