单调栈实际上就是栈,只是利用了一些巧妙的逻辑,使得每次新元素入栈后,栈内的元素都保持有序。
单调栈模板
单调栈一般用来解决一类问题:Next Greater Number
。比如说,输入一个数组 nums = [2,1,2,4,3],你返回数组 [4,2,4,-1,-1]。即找到每个元素之后,第一个大于它的元素,如果没有则设置为-1。
解决方式:使用一个栈st,然后逆序来看nums数组,先将所有栈中比当前元素小的全部弹出(比当前元素矮的元素都是后续无法利用的无效信息,如图,矮个子会被高个子挡住,因此丢弃),然后如果此时栈空,则结果是-1;如果不为空,为结果是栈顶元素。最后将当前元素入栈;循环执行,最后得出结果数组。
例题1
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
map<int,int>mp;
stack<int>st;
for(int i=nums2.size()-1;i>=0;i--){
while(!st.empty() && st.top()<nums2[i]){
st.pop();
}
if(st.empty()){
mp[nums2[i]]=-1;
}else{
mp[nums2[i]]=st.top();
}
st.push(nums2[i]);
}
vector<int>ans;
for(auto&n:nums1){
ans.push_back(mp[n]);
}
return ans;
}
};
例题2
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
stack<int>st;
vector<int>ans(temperatures.size()); //如果不预先申请长度,则会因为频繁扩容和复制数组,导致超时
for(int i=temperatures.size()-1;i>=0;i--){
int n=temperatures[i];
while(!st.empty() && n>=temperatures[st.top()]){
st.pop();
}
if(st.empty())
ans[i]=0;
else
ans[i]=st.top()-i;
st.push(i);
}
return ans;
}
};
例题3
解决循环数组问题的常用解决方法就是数组翻倍。
这里并没有直接构建一个双倍数组,而是通过下标小技巧实现的,形成逻辑上的二倍数组。
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int len=nums.size();
vector<int>ans(len,-1);
stack<int>st;
for(int i=2*len-1;i>=0;i--){
while(!st.empty() && nums[i%len]>=st.top())
st.pop();
if(i<len && !st.empty()){
ans[i]=st.top();
}
st.push(nums[i%len]);
}
return ans;
}
};