class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
Arrays.fill(ans, -1);
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n * 2; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i % n]) {
ans[stack.pop()] = nums[i % n];
}
stack.push(i % n);
}
return ans;
}
}
思路二:for循环从后往前遍历,元素倒序入栈,正序出栈 利用循环数组的方式模拟数组长度翻倍
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 2 * n - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= nums[i % n]) {
stack.pop();
}
ans[i % n] = stack.isEmpty() ? -1 : stack.peek();
stack.push(nums[i % n]);
}
return ans;
}
}
leetcode-503-下一个更大元素II
最新推荐文章于 2024-06-24 09:27:52 发布