题目:
参考:https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
栈解法
class Solution {
public:
int trap(vector<int>& height) {
/*
*给定n个非负整数表示每个宽度为1的柱子的高度图,
*计算按此排列的柱子,下雨之后能接多少雨水。
*栈:对于当前柱子,如果高度比栈顶的小,入栈;
*如果高度大于栈顶,说明栈顶柱子高度介于前一个和
*当前柱子
*/
int n = height.size();
if(n <= 2) return 0;
int sum = 0;
stack<int> st;
st.push(0);
for(int i = 1,x;i < n;i++) {
while(!st.empty() && height[st.top()] <= height[i]) {
x = st.top();st.pop();
if(!st.empty()) {
sum += (min(height[st.top()],height[i])-height[x])*(i-st.top()-1);
printf("id:%d s:%d\n ",i,sum);
}
}
st.push(i);
}
return sum;
}
};
双指针
class Solution {
public:
int trap(vector<int>& height) {
/*
*给定n个非负整数表示每个宽度为1的柱子的高度图,
*计算按此排列的柱子,下雨之后能接多少雨水。
*双指针:能盛水的柱子必然其左侧和右侧都高于它,
*由木桶理论,每次舍去左右侧较短的,移动指针,
*更新答案,直到遇到比当前短柱子更大的柱子
*/
int n = height.size();
if(n <= 2) return 0;
int sum = 0;
int l = 0,r = n-1,pos;
while(l < r) {
if(height[l] < height[r]) {
pos = l+1;
while(pos <=r && height[pos] <= height[l]) {
sum += height[l]-height[pos];
pos++;
}
l = pos;
}else {
pos = r-1;
while(pos >= l && height[pos] <= height[r]) {
sum += height[r]-height[pos];
pos--;
}
r = pos;
}
}
return sum;
}
};