单调栈~~~

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


介绍

经典问题
求数组中各个元素左侧最近的小于它的数,以及右侧最近的小于它的数。

  • 1.无重复元素:数组中元素从左往右入栈,需要保证栈中元素严格单调递减,即栈低最小,那么在每个元素入栈时,若栈顶元素大于待入栈元素,使栈顶元素出栈,那么栈顶元素的底下元素为栈顶元素的左侧最近的“小于它”的数组元素,使栈顶元素弹出的元素为栈顶元素的右侧最近的“小于它”的数组元素。

  • 2.有重复元素:方法如上,只是多一步,需要倒着遍历一遍,若该元素标记的右侧最近小元素与其相等,那么更改为其“右侧”的“右侧”(左侧无需修正)。

一.经典例题

1.每日温度


https://leetcode.cn/problems/iIQa4I/description/

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& t) {
        int stack[100002],top=0,n=t.size();
        vector<int> ans(n);
        for(int i=n-1;i>=0;i--){
            while(top>0 && t[i]>=t[stack[top-1]]){
                ans[stack[top-1]]= top==1 ? 0 : stack[top-2]-stack[top-1];
                top--;
            }
            stack[top]=i;
            top++;
        }
        while(top>0){
            ans[stack[top-1]]= top==1 ? 0 : stack[top-2]-stack[top-1];
            top--;
        }
        return ans;
    }
};

该题我没有从左到右遍历,而是从从右到左遍历,因为数组有重复值,这样可以避免最后多做一步修正,因为每个数的“右侧最近小于"是准确的无需修正的

2.子数组的最小值之和


https://leetcode.cn/problems/sum-of-subarray-minimums/description/

我们考虑数组中每个元素,考虑其参与到了多少个数组中计算,我们发现数组数等于m(距离其“左侧最近且小于”的元素的长度)*n(距离其“右侧最近且小于等于”的元素的长度))(一边小于,一边小于等于,正好避免了重复元素所造成的重复性,很奇妙吧,think about it~~)

class Solution {
public:
    int sumSubarrayMins(vector<int>& arr) {
        int n=arr.size(),top=0;
        int stack[30001];
        int m[30001][2];
        int mod=1e9+7;
        for(int i=0;i<n;i++){
            while(top>0 && arr[i]<=arr[stack[top-1]]){
                m[stack[top-1]][0]= top==1 ? stack[top-1]+1 : stack[top-1]-stack[top-2];
                m[stack[top-1]][1]= i-stack[top-1];
                top--;
            }
            stack[top]=i;
            top++;
        }
        while(top>0){
            m[stack[top-1]][0]= top==1 ? stack[top-1]+1 : stack[top-1]-stack[top-2];
            m[stack[top-1]][1]= n-stack[top-1];
            top--;
        }
        long long ans=0;
        for(int i=0;i<n;i++){
            ans=(ans+arr[i]*m[i][0]%mod*(long long)1*m[i][1]%mod)%mod;
        }
        return ans;
    }
};

3.柱状图中的最大矩形


https://leetcode.cn/problems/0ynMMM/description/

class Solution {
public:
    int largestRectangleArea(vector<int>& h) {
        int top=0,n=h.size();
        vector<int> stack(n+1);
        int ans=0;
        for(int i=0;i<n;i++){
            while(top>0 && h[i]<=h[stack[top-1]]){
                int x0= top==1 ? stack[top-1]+1 : stack[top-1]-stack[top-2];
                int x1= i-stack[top-1];
                ans=max(ans,(x0+x1-1)*h[stack[top-1]]);
                top--;
            }
            stack[top]=i;
            top++;
        } 
        while(top>0){
            int x0= top==1 ? stack[top-1]+1 : stack[top-1]-stack[top-2];
            int x1= n-stack[top-1];
            ans=max(ans,(x0+x1-1)*h[stack[top-1]]);
            top--;
        }
        return ans;
        
    }
};

4.最大矩形


https://leetcode.cn/problems/PLYXKQ/description/

考虑以每一行为底的矩形,分别算出最大面积,然后取整体最大

class Solution {
public:
    int maximalRectangle(vector<string>& s) {
        int m[201][201];
        int stack[201],top,ans=0;
        int row=s.size();
        if(row==0)return 0;
        int col=s[0].length(); 
        for(int i=0;i<col;i++){
            m[0][i]=s[0][i]-'0';
        }
        for(int i=1;i<row;i++){
            for(int j=0;j<col;j++){
                m[i][j]=(s[i][j]=='0') ? 0 : m[i-1][j]+1;
            }
        }
        for(int i=0;i<row;i++){
            top=0;
            for(int j=0;j<col;j++){
                while(top>0 && m[i][j]<=m[i][stack[top-1]]){
                    int x0= top==1 ? stack[top-1]+1 : stack[top-1]-stack[top-2];
                    int x1= j-stack[top-1];
                    ans=max(ans,(x0+x1-1)*m[i][stack[top-1]]);
                    top--;
                }
                stack[top]=j;
                top++;
            }
            while(top>0){
                int x0= top==1 ? stack[top-1]+1 : stack[top-1]-stack[top-2];
                int x1= col-stack[top-1];
                ans=max(ans,(x0+x1-1)*m[i][stack[top-1]]);
                top--;
            }
        }
        return ans;
    }
};

二.较难例题

1.最大宽度坡


https://leetcode.cn/problems/maximum-width-ramp/description/

class Solution {
public:
    int maxWidthRamp(vector<int>& nums) {
        int n=nums.size(),top=0,ans=0;
        int stack[50001];
        //维护一个严格单调递减的栈,如此一遍可得到所有“最大宽度坡”可能的左侧值。
        for(int i=0;i<n;i++){
            if(top==0 || nums[i]<nums[stack[top-1]])stack[top++]=i;
        }
        //倒序遍历数组,若栈顶元素小于等于所遍历到的元素,出栈,并比较是否更新最大宽度。
        for(int i=n-1;i>=0;i--){
            if(top==0)break;
            while(top>0 && nums[i]>=nums[stack[top-1]]){
                ans=max(ans,i-stack[top-1]);
                top--;
            }
        }
        return ans;
    }
};

2.去除重复字母


https://leetcode.cn/problems/remove-duplicate-letters/description/

class Solution {
public:
    bool set[200];
    char stack[1002];
    int top=0;
    int cnt[200];
    string removeDuplicateLetters(string s) {
        for(auto c:s){
            cnt[c]++;
        }
        for(auto c:s){
            if(!set[c]){
                while(top>0 && c<stack[top-1] && cnt[stack[top-1]]>0){
                    top--;
                    set[stack[top]]=0;
                }
                set[c]=1;
                stack[top++]=c;
            }
            cnt[c]--;
        }
        string ans;
        for(int i=0;i<top;i++){
            ans+=stack[i];
        }
        return ans;
    }
};

3.使数组按非递减顺序排列


https://leetcode.cn/problems/steps-to-make-array-non-decreasing/description/

类似于大鱼吃小鱼
我们从右往左将数组元素依次压入栈内,(保持栈内从顶向下非递减),且记录两个关键量,这个元素的值以及其需要进行吃小鱼的轮数。当待入栈元素大于栈顶元素时,令栈顶元素出栈,且让待入栈元素“接替”栈顶元素的吃鱼任务,故需比较其本身的任务时间与接替的任务时间的大小,取其大者。用此方法直到可入栈。
最后遍历单调栈中元素,得到最长的“任务轮数”


class Solution {
public:
    int totalSteps(vector<int>& nums) {
        int stack[100002][2],top=0;
        int n=nums.size();
        int ans=0;
        for(int i=n-1;i>=0;i--){
            int cnt=0;
            while(top>0 && nums[i]>stack[top-1][0]){
                cnt++;
                cnt=max(cnt,stack[top-1][1]);
                top--;
            }
            stack[top][0]=nums[i];
            stack[top][1]=cnt;
            top++;
        }
        while(top>0){
            ans=max(ans,stack[top-1][1]);
            top--;
        }
        return ans;
    }
};

4.统计全1子矩形

在这里插入图片描述


https://leetcode.cn/problems/count-submatrices-with-all-ones/description/

考虑以每一行为底的全1子矩形数
对每行遍历元素,考虑每个元素时,我们计算好矩形的数量,好矩形——以该元素高度为高度上限,以 左侧最近且比该元素小的高度 和 右侧最近且比该元素小的高度 的 较大值 为高度下限 的矩形。

class Solution {
public:
    int numSubmat(vector<vector<int>>& mat) {
        int m=mat.size(),n=mat[0].size();
        int mem[151][151];
        int stack[151],top=0;
        int ans=0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                mem[i+1][j]= mat[i][j]==0 ? 0 : mem[i][j]+1;
            }
        }
        for(int i=1;i<=m;i++){
            for(int j=0;j<n;j++){
                while(top>0 && mem[i][j]<=mem[i][stack[top-1]]){
                    int x0= top==1 ? stack[top-1]+1 : stack[top-1]-stack[top-2];
                    int x1= j-stack[top-1];
                    int h1= top==1 ? 0 : mem[i][stack[top-2]];
                    int h2= mem[i][j];
                    int cen=mem[i][stack[top-1]]-max(h1,h2);
                    ans+=(x1+x0-1)*(x1+x0)/2*(cen);
                    top--;
                }
                stack[top]=j;
                top++;
            }
            while(top>0){
                int x0= top==1 ? stack[top-1]+1 : stack[top-1]-stack[top-2];
                int x1= n-stack[top-1];
                int h1= top==1 ? 0 : mem[i][stack[top-2]];
                int h2= 0;
                int cen=mem[i][stack[top-1]]-max(h1,h2);
                ans+=(x1+x0-1)*(x1+x0)/2*(cen);
                top--;
            }
        }
        return ans;
    }
};
单调栈是一种常用的数据结构,用于解决一类特定的问题,其中最常见的问题是找到数组中每个元素的下一个更大或更小的元素。在Codeforces编程竞赛中,单调栈经常被用于解决一些与数组相关的问题。 下面是单调栈的一般思路: 1. 创建一个空栈。 2. 从左到右遍历数组元素。 3. 对于每个元素,将其与栈顶元素进行比较。 - 如果当前元素小于等于栈顶元素,则将当前元素入栈。 - 如果当前元素大于栈顶元素,则将栈顶元素弹出,并将当前元素入栈。 4. 重复步骤3,直到遍历完所有元素。 这样,最后剩下的栈中元素就是没有下一个更大或更小元素的元素。在使用单调栈求解具体问题时,我们可以根据需要进行一些特定的操作。 例如,如果要找到一个数组中每个元素的下一个更大的元素,可以使用单调递减栈。具体操作如下: 1. 创建一个空栈和一个空结果数组。 2. 从左到右遍历数组元素。 3. 对于每个元素,将其与栈顶元素进行比较。 - 如果当前元素小于等于栈顶元素,则将当前元素入栈。 - 如果当前元素大于栈顶元素,则将栈顶元素弹出,并将其在结果数组中的位置记录为当前元素的下一个更大元素的索引。 4. 将当前元素入栈。 5. 重复步骤3和4,直到遍历完所有元素。 6. 结果数组中没有下一个更大元素的位置,可以设置为-1。 以下是一个使用单调递减栈求解下一个更大元素问题的示例代码: ```cpp #include <iostream> #include <stack> #include <vector> std::vector<int> nextGreaterElement(std::vector<int>& nums) { int n = nums.size(); std::vector<int> result(n, -1); std::stack<int> stack; for (int i = 0; i < n; i++) { while (!stack.empty() && nums[i] > nums[stack.top()]) { result[stack.top()] = i; stack.pop(); } stack.push(i); } return result; } int main() { std::vector<int> nums = {1,3, 2, 4, 5, 1}; std::vector<int> result = nextGreaterElement(nums); for (int i = 0; i < result.size(); i++) { std::cout << "Next greater element for " << nums[i] << ": "; if (result[i] != -1) { std::cout << nums[result[i]]; } else { std::cout << "None"; } std::cout << std::endl; } return 0; } ``` 以上代码将输出: ``` Next greater element for 1: 3 Next greater element for 3: 4 Next greater element for 2: 4 Next greater element for 4: 5 Next greater element for 5: None Next greater element for 1: None ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值