当前位置: 首页 > news >正文

Nearest Smaller Values(sorting and searching)

题目描述

Given an array of n integers, your task is to find for each array position the nearest position to its left having a smaller value.

输入

The first input line has an integer n: the size of the array.
The second line has n integers x1,x2,...,xn: the array values.
Constraints
1 ≤ n ≤ 2\times10^5
1 ≤ xi ≤ 10^9

输出

Print n integers: for each array position the nearest position with a smaller value. If there is no such position, print 0.

样例输入
8
2 5 1 4 8 3 2 5
样例输出
0 1 0 3 4 3 3 7
思路分析

1.输入处理:首先读取数组大小n,然后读取数组arr

2.初始化res数组用于存储结果,初始化为0(表示没有找到符合条件的元素)。stack用于维护单调递增的索引栈。

3.单调栈处理

遍历数组中的每个元素。

当栈非空且栈顶索引对应的元素值大于等于当前元素值时,弹出栈顶(因为这些元素不可能成为后续元素的答案)。

如果栈非空,栈顶索引对应的元素即为左边最近的小于当前元素的值,将其索引(加1转换为1-based)存入res[i]

将当前索引压入栈中。

代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,x;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>n;vector<int>arr(n);for(int i=0;i<n;i++){cin>>arr[i];}vector<int>res(n,0);vector<int>mystack;for(int i=0;i<n;i++){while(!mystack.empty()&&arr[mystack.back()]>=arr[i]){mystack.pop_back();}if(!mystack.empty()){res[i]=mystack.back()+1;}mystack.push_back(i);}for(int i=0;i<n;i++){cout<<res[i]<<" ";}return 0;
}
http://www.dtcms.com/a/321661.html

相关文章:

  • 专题二_滑动窗口_最大连续1的个数
  • 用户组权限及高级权限管理:从基础到企业级 sudo 提权实战
  • 基于 Vue + 高德地图实现卫星图与 Mapbox 矢量瓦片
  • Claude Code:智能代码审查工具实战案例分享
  • 流形折叠与条件机制
  • C++学习笔记
  • “鱼书”深度学习进阶笔记(1)第二章
  • 从零构建桌面写作软件的书籍管理系统:Electron + Vue 3 实战指南
  • 智慧农业温室大棚物联网远程监控与智能监测系统
  • Nginx反向代理教程:配置多个网站并一键开启HTTPS (Certbot)
  • git reset
  • Maven/Gradle常用命令
  • 14. isaacsim4.2教程-April Tags/给相机加噪声
  • GPT-5发布:AI竞赛进入新阶段
  • Spring Boot Redis 缓存完全指南
  • ApiPost 设置统一URL前缀
  • 计算机基础速通--数据结构·串的应用
  • 医防融合中心-智慧化慢病全程管理医疗AI系统开发(中)
  • 元数据管理与数据治理平台:Apache Atlas 构建与安装 Building Installing Apache Atlas
  • 有哪些产品需要遵循ASTM D4169-23e1
  • 【ee类保研面试】其他类---计算机网络
  • 操作系统:多线程模型(Multithreading Models)与超线程技术(Hyperthreading)
  • AI漫画翻译器-上传图片自动翻译,支持多语言
  • 学习Java的Day27
  • 基于ffmpeg和rk3588的mpp编解码库多路融屏程序设计
  • Git 基础操作笔记(速查)
  • 嵌入式Linux学习 - 数据结构6
  • 【设计模式】抽象工厂模式 (工具(Kit)模式)
  • PPT科研绘图实践笔记(持续更新)
  • AI 编程工具使用心得与对比评测