当前位置:网站首页>单调栈-503. 下一个更大元素 II
单调栈-503. 下一个更大元素 II
2022-07-03 08:24:00 【later_rql】
1.解题思路
首先,确定本题的解题思路,题目要求记录每个数右边的大于该数的数值,实质就是向右找最近的一个大于当前数的值,而且题目说明该数组是循环数组。
确定使用单调栈来解决本题:
单调栈的使用场景:通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了。

2.难点
本题稍加一点难度,就是将数组变成的循环数组,只需要对其做取余操作即可。
3.代码
public int[] nextGreaterElements(int[] nums) {
int len=nums.length;
int[] result=new int[nums.length];
for (int i=0;i<result.length;i++){
result[i]=-1;
}
Stack<Integer> stack = new Stack<>();
stack.push(0);
for (int i=1;i<len*2;i++){
while (!stack.isEmpty() && nums[(i%len)]>nums[stack.peek()]){
if (result[stack.peek()]==-1){
result[stack.peek()]=nums[i%len];
}
stack.pop();
}
stack.push(i%len);
}
return result;
}
4.性能
- 时间复杂度:O(n)
- 空间复杂度:O(n)
边栏推荐
- C language - Introduction - essence Edition - take you into programming (I)
- Flex flexible box layout
- Simply start with the essence and principle of SOM neural network
- 详解sizeof、strlen、指针和数组等组合题
- UE4 source code reading_ Bone model and animation system_ Animation compression
- C#课程设计之学生教务管理系统
- Shader foundation 01
- Un système de gestion de centre commercial pour la conception de cours de technologie d'application de base de données
- 梯度下降法求解BP神经网络的简单Demo
- [linear table] basic operation of bidirectional linked list specify node exchange
猜你喜欢
![P1596 [USACO10OCT]Lake Counting S](/img/a7/07a84c93ee476788d9443c0add808b.png)
P1596 [USACO10OCT]Lake Counting S

Unity editor expansion - scrolling list

Mall management system of database application technology course design

Notes on understanding applets 2022/7/3

php-fpm软件的安装+openresty高速缓存搭建

详解sizeof、strlen、指针和数组等组合题

CLion-Toolchains are not configured Configure Disable profile问题解决

了解小程序的笔记 2022/7/3

C语言-入门-精华版-带你走进编程(一)

C#课程设计之员工信息管理系统
随机推荐
String class
Simply start with the essence and principle of SOM neural network
Abstract classes and interfaces
[set theory] order relation (hastu example | divisive relation hastu | inclusive relation hastu | refinement relation hastu)
Osgconv tool usage
MXone Pro自适应2.0影视模板西瓜视频主题苹果cmsV10模板
简易入手《SOM神经网络》的本质与原理
[audio and video] ijkplayer error code
C语言-入门-精华版-带你走进编程(一)
VIM learning notes from introduction to silk skating
【K&R】中文第二版 个人题解 Chapter1
C#课程设计之员工信息管理系统
Ue5 opencv plug-in use
Map的实现类的顺序性
go 解析身份证
十六进制编码简介
Haproxy+kept cluster setup 02
MAE
Dealing with duplicate data in Excel with xlwings
Golang's range