42.接雨水
我的解法:
单调栈:栈中保留height元素下标,从栈底到栈顶的下标对应的数组元素值从大到小
- 创建栈m_stack,向其中插入元素0;
- 接着从下标1开始遍历height的各个元素
(1)若height[i]小于栈顶元素对应的height数组值,则直接向m_stack中插入i;
(2)若height[i]等于栈顶元素对应的height数组值,则弹出栈顶元素后再插入i;
相同元素保留只最右边的
(3)若height[i]大于栈顶元素对应的height数组值,此时可接雨水:
栈顶作为凹槽,当前元素是凹槽右边,栈中前一元素是凹槽左边
class Solution{
public:
int trap(vector<int>& height){
stack<int> m_stack;
m_stack.push(0);
int sum = 0;
for(int i = 1; i < height.size(); ++i){
if(height[i] < height[m_stack.top()]){
m_stack.push(i);
}
else if(height[i] == height[m_stack.top()]){
m_stack.pop();
m_stack.push(i);
}
else{
while(!m_stack.empty() && height[i] > height[m_stack.top()]){
int tmp = height[m_stack.top()];
m_stack.pop();
if(!m_stack.empty()){
int h = min(height[i],height[m_stack.top()]) - tmp;
int w = i - m_stack.top() - 1;
sum += h * w;
}
}
m_stack.push(i);
}
}
return sum;
}
};