1. 程式人生 > 其它 >使用單調棧判斷每個陣列離自己最近的比自己小的值

使用單調棧判斷每個陣列離自己最近的比自己小的值

//
// 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
主要是給自己看的,所以肯定會出現很多錯誤哈哈哈哈哈