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

GAMES104 作业2-ColorGrading

Chapter IX app project test (3) test tools

从遇见大咖到成为大咖,昇腾AI开发者创享日给开发者带来无限可能

数据库系列之MySQL和TiDB中慢日志分析

Lost connection repair: make "hide and seek" nowhere to hide

Hot! Yolov6's fast and accurate target detection framework is open source (with source code download)

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

Anaconda命令用法

Resource management, high availability and automation (medium)

17 `bs object Node name h3 Parent ` parents get parent node ancestor node
随机推荐
Tardigrade: Trino's solution to ETL scenarios
力扣每日一题-第29天-575.分糖果
matlab习题 —— 符号运算相关练习
《Go题库·12》slice和array区别?
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3
How does the open-ended Hall current sensor help the transformation of DC power distribution?
Resource management, high availability and automation (medium)
composition api在项目中的使用总结
TypeError:&nbsp;&#039;module&amp;#03…
Chapter IX app project test (3) test tools
基于 LNMP 搭建个人网站的填坑之旅
idea自动生成代码
WPF 下的自定义控件以及 Grid 中控件的自适应
kubernetes资源对象介绍及常用命令
数字有为,易步到位 华为携“5极”明星产品加速布局商业市场
STM32 peripheral SDIO and SD card configuration
新手开哪家的证券账户是比较好?股票开户安全吗
可扩展数据库(下)
How to automatically add author, time, etc. to eclipse
数的每一位平方和