当前位置:网站首页>单调栈-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)
边栏推荐
- Clion toolchains are not configured configure disable profile problem solving
- Kunlunbase meetup is waiting for you!
- Solution détaillée de toutes les formules de fonction de transfert (fonction d'activation) du réseau neuronal MATLAB
- Conversion between string and int types in golang
- String class
- Mysql容器化(1)Docker安装MySQL
- Creation and content of mapnode -- osgearth rendering engine series (2)
- Osganimation library parsing
- One dimensional array two dimensional array (sort Max insert sort)
- go 解析身份证
猜你喜欢

二进制转十进制,十进制转二进制

Graphics_ Learnopongl learning notes

【云原生】微服务之Feign的介绍与使用

Creation of osgearth earth files to the earth ------ osgearth rendering engine series (1)

About the problem that the editor and the white screen of the login interface cannot be found after the location of unityhub is changed

Notes on understanding applets 2022/7/3
![[set theory] order relation (hastu example | divisive relation hastu | inclusive relation hastu | refinement relation hastu)](/img/de/1c75b5e7ed79aca47462de365428a7.jpg)
[set theory] order relation (hastu example | divisive relation hastu | inclusive relation hastu | refinement relation hastu)

简易入手《SOM神经网络》的本质与原理

Three characteristics

Clion toolchains are not configured configure disable profile problem solving
随机推荐
100 GIS practical application cases (78) - Multi compliance database design and data warehousing
Encoding and decoding of golang URL
796 · 开锁
二进制转十进制,十进制转二进制
Unity editor expansion - scrolling list
Kwai 20200412 recruitment
Haproxy+kept cluster setup 02
Redis data structure
Golang 时间格式整理
Unity Editor Extension - event handling
Redis的数据结构
[audio and video] ijkplayer error code
Ue5 opencv plug-in use
Maxcompute string splitting function -split_ PART
Transplantation of freetype Library
Dotween plug-in
【更新中】微信小程序学习笔记_3
swagger文档配置
Abstract classes and interfaces
Osgearth north arrow display