未验证 提交 5a8a7a37 编写于 作者: J JiangangZhao 提交者: GitHub

Update 单调栈.md

【503.下一个更大元素II】【java】
上级 36f59b6f
......@@ -181,4 +181,38 @@ vector<int> nextGreaterElements(vector<int>& nums) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ No newline at end of file
======其他语言代码======
【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;
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册