当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

「运维有小邓」监控文件及文件夹变更

用Pycharm开发Flask框架设置debug模式没有效果的解决办法

如何系统学习一门编程语言? | 黑马程序员

Import an excel file, solve the problem of skipping blank cells without reading and moving the subscript forward, and return_ BLANK_ AS_ Null red

数据库系列之MySQL配置F5负载均衡

Summary of SQL basic syntax for C #

Object class, and__ new__,__ init__,__ setattr__,__ dict__

Websocket (simple experience version)

荣耀v8 真机调试时不显示 Logcat 日志的解决办法

多线程与高并发三:AQS底层源码分析及其实现类
随机推荐
第二轮红队免费公开课来袭~明晚八点!
基于 WPF 的酷炫 GUI 窗口的简易实现
数组的方法
collections. Use of defaultdict()
Li Kou daily question - day 29 -1491 Average wage after removing minimum wage and maximum wage
可扩展系统的“9不”原则和“5个”衡量维度
物体上下漂浮工具
Automatic backup of MySQL database
大咖说·计算讲谈社|什么是东数西算要解决的核心问题?
小程序的防抖节流怎么写?
Sublime text 3 basic configuration tutorial
荣耀v8 真机调试时不显示 Logcat 日志的解决办法
多线程与高并发六:线程池源码解析
从遇见大咖到成为大咖,昇腾AI开发者创享日给开发者带来无限可能
matlab习题 —— 符号运算相关练习
idea自动生成代码
如何给Eclips自动添加作者,时间等…
matlab习题 —— 数据的基本处理
可扩展存储系统(上)
Chapter IX app project test (3) test tools