未验证 提交 47c62fe8 编写于 作者: B BruceCat 提交者: GitHub

【503.下一个更大元素II】【java】

【503.下一个更大元素II】【java】
......@@ -239,6 +239,7 @@ public int[] nextGreaterElement(int[] nums1, int[] nums2) {
}
```
[ZakAnun](https://github.com/ZakAnun) 提供代码
```java
// 739. Daily Temperatures
......@@ -258,4 +259,39 @@ class Solution {
return ans;
}
}
```
[JiangangZhao](https://github.com/JiangangZhao)提供【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;
}
}
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册