当前位置:网站首页>单调栈-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)
边栏推荐
- P1596 [USACO10OCT]Lake Counting S
- Pit & ADB wireless debugging of vivo real machine debugging
- Sequence of map implementation classes
- Detailed explanation of all transfer function (activation function) formulas of MATLAB neural network
- 数据库应用技术课程设计之商城管理系统
- Find the intersection of line segments
- Visual Studio (VS) shortcut keys
- Mall management system of database application technology course design
- php-fpm软件的安装+openresty高速缓存搭建
- 【云原生】微服务之Feign的介绍与使用
猜你喜欢

Dotween plug-in

十六进制编码简介

Some understandings of 3dfiles

UE4 source code reading_ Bone model and animation system_ Animation process

Simple demo of solving BP neural network by gradient descent method

Solution détaillée de toutes les formules de fonction de transfert (fonction d'activation) du réseau neuronal MATLAB

Jupyter remote server configuration and server startup

C course design employee information management system

Graphics_ Games101/202 learning notes

Mxone Pro adaptive 2.0 film and television template watermelon video theme apple cmsv10 template
随机推荐
[public key cryptography] ECC elliptic cryptosystem (implementing ElGamal encryption method)
Conversion between golang JSON format and structure
matlab神經網絡所有傳遞函數(激活函數)公式詳解
Unity notes 1
LinkList
String class
Some understandings of 3dfiles
Golang's range
Installation of PHP FPM software +openresty cache construction
Osgearth starry background
Unity editor expansion - the framework and context of unity imgui
Creation of osgearth earth files to the earth ------ osgearth rendering engine series (1)
Unity interactive water ripple post-treatment
C语言-入门-精华版-带你走进编程(一)
Display terrain database on osgearth ball
About the problem that the editor and the white screen of the login interface cannot be found after the location of unityhub is changed
Find the intersection of line segments
C#课程设计之员工信息管理系统
Markdown directory generation
Intersectionpicker in osgearth