当前位置:网站首页>单调栈-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)
边栏推荐
- Unity editor expansion - controls, layouts
- MAE
- 【更新中】微信小程序学习笔记_3
- Downward compatibility and upward compatibility
- Ue5 opencv plug-in use
- MySQL containerization (1) docker installation MySQL
- UE4 plug in development
- Base64和Base64URL
- Golang 中string和int类型相互转换
- C language - Introduction - essence Edition - take you into programming (I)
猜你喜欢

ArrayList

Unity change default editor

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

KunlunBase MeetUP 等您来!

Jupyter remote server configuration and server startup

100 GIS practical application cases (78) - Multi compliance database design and data warehousing

Three characteristics

How to establish rectangular coordinate system in space

matlab神经网络所有传递函数(激活函数)公式详解

Image processing 8-cnn image classification
随机推荐
C语言-入门-精华版-带你走进编程(一)
Swagger document configuration
Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)
Osgearth target selection
Gradle's method of dynamically modifying APK package name
Intersectionpicker in osgearth
E: Unable to locate package ROS melody desktop full
二进制转十进制,十进制转二进制
Minimap plug-in
Find the intersection of line segments
Unity Editor Extension - Outline
Simple demo of solving BP neural network by gradient descent method
[audio and video] ijkplayer error code
Ue5 opencv plug-in use
VIM learning notes from introduction to silk skating
Unity interactive water ripple post-treatment
MySQL containerization (1) docker installation MySQL
php-fpm软件的安装+openresty高速缓存搭建
MXone Pro自适应2.0影视模板西瓜视频主题苹果cmsV10模板
Osgconv tool usage