当前位置:网站首页>单调栈-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)
边栏推荐
- redis集群系列四
- 【云原生】微服务之Feign的介绍与使用
- Multi traveling salesman problem -- overview of formula and solution process
- 十六进制编码简介
- C#课程设计之学生教务管理系统
- animation
- VIM learning notes from introduction to silk skating
- Notes on understanding applets 2022/7/3
- Osgearth north arrow display
- Constraintlayout's constraintset dynamically modifies constraints
猜你喜欢

Constraintlayout's constraintset dynamically modifies constraints

animation
![[updating] wechat applet learning notes_ three](/img/05/958b8d62d3a42b38ca1a2d8631a7f8.png)
[updating] wechat applet learning notes_ three

VIM learning notes from introduction to silk skating

Display terrain database on osgearth ball

MAE

Mxone Pro adaptive 2.0 film and television template watermelon video theme apple cmsv10 template

Use of ue5 QRcode plug-in
![P1596 [USACO10OCT]Lake Counting S](/img/a7/07a84c93ee476788d9443c0add808b.png)
P1596 [USACO10OCT]Lake Counting S

Redis data structure
随机推荐
[cloud native] introduction and use of feign of microservices
Advanced OSG collision detection
MAE
Easy touch plug-in
Unity editor expansion - controls, layouts
Redis cluster series 4
Golang url的编码和解码
Dotween plug-in
Shader foundation 01
Transmit pictures with Base64 encoding
Redis的数据结构
VIM learning notes from introduction to silk skating
Delete the last character of the string in golang
OpenGL learning notes
UE4 call DLL
GIS实战应用案例100篇(七十八)-多规合一数据库设计及数据入库
Unity editor expansion - scrolling list
Detailed explanation of all transfer function (activation function) formulas of MATLAB neural network
Graphics_ Games101/202 learning notes
Transplantation of freetype Library