单调栈

Posted by Liao on 2020-03-24

单调栈

简介

单调栈分为单调递增栈和单调递减栈,顾名思义就是栈内元素大小保持递增或递减。

操作规则(以单调递增栈为例)

如果新进来的元素栈顶元素大,则进栈

如果新进的元素栈顶元素小,就把栈内元素出栈,直到找到第一个比新进元素要小的元素为止。

代码模板

1
2
3
4
5
6
7
8
9
int MonotoneStack(vector<int>& height){
stack<int>st;
for(int i = 0; i < height.size(); i++){
while(!st.empty() && height[st.top()] >= height[i]){

}
st.push(i);
}
}

例题

LeetCode 接雨水

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int trap(vector<int>& height) {
int n = height.size();
if(n < 3){
return 0;
}
int ans = 0;
stack<int>st;
for(int i = 0; i < n; i++){
while(!st.empty() && height[i] > height[st.top()]){
int top = st.top();
st.pop();
if(st.empty())
break;
int width = i - st.top() - 1;
int h = min(height[i],height[st.top()]) - height[top];
ans += width * h;
}
st.push(i);
}
return ans;
}

Leetcode 柱状图中最大的矩形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int>st;
int ans = 0;
heights.push_back(0);
for(int i = 0; i < heights.size(); i++){
while(!st.empty() && heights[st.top()] >= heights[i]){
int h = heights[st.top()];
st.pop();
if(st.empty()){
ans = max(ans, i * h);
}
else{
ans = max(ans,(i-st.top()-1)*h);
}
}
st.push(i);
}
return ans;
}
};

参考