当前位置:网站首页>leetcode:单调栈结构(进阶)
leetcode:单调栈结构(进阶)
2022-06-28 03:06:00 【OceanStar的学习笔记】
题目来源
题目描述


题目解析
#include <vector>
#include <iostream>
std::vector<int> arr(1000000);
std::vector<std::vector<int>> ans(1000000, std::vector<int>(2));
// stack1 : 相等值的位置也放
// stack2 : 只放不相等值的最后一个位置
// 比如 : arr = { 3, 3, 3, 4, 4, 6, 6, 6}
// 位置 0 1 2 3 4 5 6 7
// 如果位置依次压栈,
// stack1中的记录是(位置) : 0 1 2 3 4 5 6 7
// stack1中的记录是(位置) : 2 4 7
std::vector<int> stack1(1000000);
std::vector<int> stack2(1000000);
void getNearLess(int n){
int stackSize1 = 0;
int stackSize2 = 0;
for (int i = 0; i < n; ++i) {
while (stackSize1 > 0 && arr[stack1[stackSize1 - 1]] > arr[i]) {
int curIndex = stack1[--stackSize1];
int left = stackSize2 < 2 ? -1 : stack2[stackSize2 - 2];
ans[curIndex][0] = left;
ans[curIndex][1] = i;
if (stackSize1 == 0 || arr[stack1[stackSize1 - 1]] != arr[curIndex]) {
stackSize2--;
}
}
if (stackSize1 != 0 && arr[stack1[stackSize1 - 1]] == arr[i]) {
stack2[stackSize2 - 1] = i;
} else {
stack2[stackSize2++] = i;
}
stack1[stackSize1++] = i;
}
while (stackSize1 != 0) {
int curIndex = stack1[--stackSize1];
int left = stackSize2 < 2 ? -1 : stack2[stackSize2 - 2];
ans[curIndex][0] = left;
ans[curIndex][1] = -1;
if (stackSize1 == 0 || arr[stack1[stackSize1 - 1]] != arr[curIndex]) {
stackSize2--;
}
}
}
int main()
{
int n ;
std::cin >> n;
for (int i = 0; i < n; ++i) {
std::cin >> arr[i];
}
getNearLess(n);
std::string builder;
for (int i = 0; i < n; ++i) {
builder = builder + std::to_string(ans[i][0]) + " " + std::to_string(ans[i][1]) + "\n";
}
std::cout << builder << "\n";
return 0;
}
边栏推荐
- 数据库系列之InnoDB中在线DDL实现机制
- Online DDL implementation mechanism in InnoDB of database Series
- 数据库系列之MySQL中的分页查询优化
- 力扣每日一题-第29天-219.存在重复元素Ⅱ
- 数据库系列之MySQL中的执行计划
- Build your own website (17)
- What is the difference between slice and array in go question bank 12?
- 数据库系列之MySQL和TiDB中慢日志分析
- Li Kou daily question - day 29 -219 Duplicate Element II exists
- INFO:&nbsp;HHH000397:&nbsp;Using…
猜你喜欢
随机推荐
电子地图坐标系统研究整理
Is it better for a novice to open a securities account? Is it safe to open a stock trading account
数据库系列之MySQL配置F5负载均衡
View the SQL execution plan according to explain and optimize the SQL
数组的方法
TypeError:&nbsp;&#039;module&amp;#03…
Research and arrangement of electronic map coordinate system
解析STEAM教育框架下未来教师研究能力
WARN:&nbsp; SQL&nbsp; Error:&nbsp;…
SSH框架的搭建(下)
在牛客中使用JS编程题【split】
Use js programming questions [split] in Niuke
matlab习题 —— 数据的基本处理
Resource management, high availability and automation (medium)
No&nbsp; result&nbsp; defined&amp; nbsp…
如何给Eclips自动添加作者,时间等…
Import an excel file, solve the problem of skipping blank cells without reading and moving the subscript forward, and return_ BLANK_ AS_ Null red
荣耀v8 真机调试时不显示 Logcat 日志的解决办法
密码加密md5和加盐处理
CURDATE()和NOW()区别








