題目:
分析:這道題是原題的一個變形,原題可看這裏 ,不同的是本題的數組是可循環的並且不找與更大元素的距離而是找到它,同樣使用棧即可解決
代碼:
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;
}
}