使用单调栈判断每个数组离自己最近的比自己小的值
//
// 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
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律