当前位置:网站首页>Leetcode: monotonic stack structure (Advanced)
Leetcode: monotonic stack structure (Advanced)
2022-06-28 03:53:00 【Oceanstar's learning notes】
Title source
Title Description


title
#include <vector>
#include <iostream>
std::vector<int> arr(1000000);
std::vector<std::vector<int>> ans(1000000, std::vector<int>(2));
// stack1 : Position of equal value
// stack2 : Only put the last position of unequal values
// such as : arr = { 3, 3, 3, 4, 4, 6, 6, 6}
// Location 0 1 2 3 4 5 6 7
// If the positions are stacked in turn ,
// stack1 The record in is ( Location ) : 0 1 2 3 4 5 6 7
// stack1 The record in is ( Location ) : 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;
}
边栏推荐
- 解析教育机器人的综合应用能力
- Automatic backup of MySQL database
- What is the core problem to be solved in the East and West?
- Extensible database (I)
- Floating point and complex type of go data type (4)
- Database migration
- WebSocket(简单体验版)
- How does the open-ended Hall current sensor help the transformation of DC power distribution?
- 力扣每日一题-第29天-219.存在重复元素Ⅱ
- Change of monitoring documents and folders of "operation and maintenance department"
猜你喜欢
随机推荐
Execution plan in MySQL of database Series
Does the applet input box flash?
开启创客教育造物学的领域
Pycharm不同项目之间共用第三方模块
荣耀v8 真机调试时不显示 Logcat 日志的解决办法
Learning - useful resources
Pycharm setting pseudo sublime color scheme
自用工具 猴子都会用的unity视频播放器
Arrangement of basic electrical knowledge (I)
密码加密md5和加盐处理
Huawei equipment WLAN basic service configuration command
双亲委派机制的理解学习
database
测不准原理
TypeError:&nbsp;&#039;module&amp;#03…
What is the difference between slice and array in go question bank 12?
JVM一:JVM入门以及Class文件认识
数据库
Lost connection repair: make "hide and seek" nowhere to hide
Object floating tool









