class Solution {
public:
int trap(vector<int>& height) {
if (height.size() <= 2) {
return 0;
}
int maxIndex = 0, maxNum = height[0];
for (int i = 1; i < height.size(); i++) {
if (height[i] > maxNum) {
maxNum = height[i];
maxIndex = i;
}
}
int result = 0;
stack<int>stk;
for (int i = 0; i <= maxIndex; i++) {
if (stk.empty()) {
stk.push(height[i]);
}
else if (height[i] < stk.top()) {
result += (stk.top() - height[i]);
}
else {
stk.pop();
stk.push(height[i]);
}
}
stk.pop();
for (int i = height.size() - 1; i >= maxIndex; i--) {
if (stk.empty()) {
stk.push(height[i]);
}
else if (height[i] < stk.top()) {
result += (stk.top() - height[i]);
}
else {
stk.pop();
stk.push(height[i]);
}
}
return result;
}
};
42-接雨水(单调递减栈)
最新推荐文章于 2022-11-05 18:37:35 发布