mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-05 03:36:39 +08:00
Update 单调栈.md
【503.下一个更大元素II】【java】
This commit is contained in:
@ -181,4 +181,38 @@ vector<int> nextGreaterElements(vector<int>& nums) {
|
||||
<img src="../pictures/qrcode.jpg" width=200 >
|
||||
</p>
|
||||
|
||||
======其他语言代码======
|
||||
======其他语言代码======
|
||||
|
||||
【503.下一个更大元素II】【java】
|
||||
```java
|
||||
class Solution {
|
||||
public int[] nextGreaterElements(int[] nums) {
|
||||
//数组长度
|
||||
int n = nums.length;
|
||||
//逻辑拼接,数组长度翻倍
|
||||
int len = n*2 - 1;
|
||||
//存储结果数组
|
||||
int[] res = new int[n];
|
||||
//存放索引,不是元素
|
||||
LinkedList<Integer> s = new LinkedList<>();
|
||||
//从前往后遍历
|
||||
for (int i = 0; i < len; ++i) {
|
||||
//索引要取模
|
||||
int val = nums[i % n];
|
||||
//当前元素比栈顶元素大,即是栈顶元素的下一个更大的元素
|
||||
while (!s.isEmpty() && val > nums[s.peek()]) {
|
||||
res[s.pop()] = val;
|
||||
}
|
||||
//i<n时入栈
|
||||
if (i < n) {
|
||||
s.push(i);
|
||||
}
|
||||
}
|
||||
//栈中剩余的索引不存在下一个更大的元素,赋值-1
|
||||
while (!s.isEmpty()) {
|
||||
res[s.pop()] = -1;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user