使用单调栈判断每个数组离自己最近的比自己小的值

//
// Created by Administrator on 2021/8/12.
//

#ifndef C__TEST02_MONOTONOUSSTACK_HPP
#define C__TEST02_MONOTONOUSSTACK_HPP

#include <iostream>
#include <vector>
#include <list>
#include <stack>
using namespace std;

class MonotonousStack {
public:
    static vector<vector<int>> getLNearLessNoRepeat(vector<int> &arr){
        if(arr.empty()){return {{}};}
        //建立一个和arr数组大小一样的行数,列数是2表示左右两端
        vector<vector<int>> res(arr.size());
        for(auto &it:res){
            it.resize(2);
        }

        //s里面放的是数组下标
        stack<int> s; //从栈底到栈顶从小到大的单调栈

        for(int i = 0; i < arr.size(); ++i){
            while(!s.empty() && arr[s.top()] > arr[i]){
                //当前节点弹出
                int curIndex = s.top();
                s.pop();
                int leftLessIndex = s.empty() ? -1:s.top();
                res[curIndex][0] = leftLessIndex;
                res[curIndex][1] = i;
            }
            s.push(i);
        }
        while(!s.empty()){
            int curIndex = s.top();
            s.pop();
            int leftLessIndex = s.empty()?-1:s.top();
            res[curIndex][0] = leftLessIndex;
            res[curIndex][1] = -1;
        }
        return res;
    }
    static void test01(){
        vector<int> A = {4,5,6,7,8,9,1};
        vector<vector<int>> res = getLNearLessNoRepeat(A);
        for(auto &it : res){
            cout<<"left: "<<it[0]<<" "<<"right: "<<it[1]<<endl;
        }
    }

    static vector<vector<int>> getLNearLess(vector<int> &arr){
        if(arr.empty()){return {{}};}
        vector<vector<int>> res(arr.size());
        for(auto &it : res){
            it.resize(2);
        }
        stack<list<int>> s;
        for(int i = 0; i < arr.size(); ++i){
            while(!s.empty() && arr[s.top().front()] > arr[i]){
                list<int> cur = s.top();
                s.pop();
                int leftLessIndex = s.empty()?-1:s.top().back();
                for(auto &it:cur){
                    res[it][0] = leftLessIndex;
                    res[it][1] = i;
                }
            }
            if(!s.empty() && arr[s.top().front()] == arr[i]){
                s.top().push_back(i);
            }else{
                list<int> newIndexList = {i};
                s.push(newIndexList);
            }
        }

        while(!s.empty()){
            list<int> cur = s.top();
            s.pop();
            int leftLessIndex = s.empty()?-1:s.top().back();
            for(auto &it:cur){
                res[it][0] = leftLessIndex;
                res[it][1] = -1;
            }
        }
        return res;
    }

    static void test02(){
        vector<int> A = {4,5,5,5,1,6,7,8,9,1};
        vector<vector<int>> res = getLNearLess(A);
        for(auto &it : res){
            cout<<"left: "<<it[0]<<" "<<"right: "<<it[1]<<endl;
        }
    }
};


#endif //C__TEST02_MONOTONOUSSTACK_HPP
posted @ 2021-09-22 18:57  蘑菇王国大聪明  阅读(46)  评论(0)    收藏  举报