单调栈的定义
单调栈,顾名思义,是维持单调递增或递减的栈
单调栈的性质
单调递增栈
单调递增栈的形式如上,适合寻找,距离他最近的,比他小的,左右两边元素
单调递减栈
与单调递增栈的用法相反
题目
84. 柱状图中最大的矩形
单调递增栈的原理
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.push_back(0); // 添加0,便于处理
stack<int> st;
int ans = 0;
for(int i = 0; i < heights.size(); i++){ // 单调栈套路
while(!st.empty() && heights[i] <= heights[st.top()]){ // 单调栈套路
int tmp = heights[st.top()]; // 单调栈套路
st.pop(); // 单调栈套路
int area = st.empty() ? tmp*i : tmp * (i - st.top() - 1); // 处理逻辑
ans = max(ans, area); // 处理逻辑
}
st.push(i); // 单调栈套路
}
return ans;
}
};
42. 接雨水
单调递减栈
class Solution {
public:
int trap(vector<int>& height) {
int ans = 0;
stack<int> st;
for(int i = 0; i < height.size(); i++){
while(!st.empty() && height[i] > height[st.top()]){
int tmp = height[st.top()];
st.pop();
if(!st.empty()){
ans += (min(height[i], height[st.top()]) - tmp)*(i - st.top() - 1);
}
}
st.push(i);
}
return ans;
}
};
739. 每日温度
这个题使用递减栈
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
int size = T.size();
vector<int> ans(size, 0);
stack<int> st;
for(int i = 0; i < size; i++){
while(!st.empty() && T[i] > T[st.top()]){
ans[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
return ans;
}
};
496. 下一个更大元素 I
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> mp;
stack<int> st;
vector<int> ret(nums1.size(), -1);
for(int i = 0; i < nums1.size(); i++){
mp[nums1[i]] = i;
}
for(int i = 0; i < nums2.size(); i++){
while(!st.empty() && nums2[i] > nums2[st.top()]){
int val = nums2[st.top()];
if(mp.find(val) != mp.end()){
int index = mp[val];
ret[index] = i;
}
st.pop();
}
st.push(i);
}
return ret;
}
};