题目:
分析:这道题是原题的一个变形,原题可看这里 ,不同的是本题的数组是可循环的并且不找与更大元素的距离而是找到它,同样使用栈即可解决
代码:
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] next = new int[nums.length];
//初始化为-1, 因为找不到为-1
for(int i = 0; i < next.length; i++){
next[i] = -1;
}
Stack<Integer> istack = new Stack<>();
for(int i = 0; i < nums.length*2; i++){
//因为可循环,所以i < nums.length*2,以便可以访问数组第二次
int current_num = nums[i%nums.length];
while(!istack.isEmpty() && current_num > nums[istack.peek()]){
next[istack.pop()] = current_num;
}
//只需把第一次遍历加进去即可,循环时就不用加了
if(i < nums.length){
istack.push(i);
}
}
return next;
}
}