用一个stack来存储之前的index
要遍历两遍array因为存在循环。
public class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] res = new int[n];
Arrays.fill(res, -1);
// use a stack to store index that value lower than current value
Stack<Integer> index = new Stack<Integer>();
for (int i = 0; i < n * 2; i++) {
int num = nums[i % n];
while (!index.isEmpty() && nums[index.peek()] < num) {
res[index.pop()] = num;
}
// push only in first round
if (i < n) index.push(i);
}
return res;
}
}
本文介绍了一种使用栈的数据结构解决寻找数组中每个元素下一个更大元素的问题,并针对具有循环特性的数组进行了特殊处理。通过两次遍历数组,确保了能够正确处理循环数组的情况。
764

被折叠的 条评论
为什么被折叠?



