思路:
// @Title: 下一个更大元素 II (Next Greater Element II)
// @Author: qisiii
// @Date: 2024-06-24 23:27:36
// @Runtime: 5 ms
// @Memory: 44.8 MB
// @comment:
// @flag:
class Solution {
public int[] nextGreaterElements(int[] nums) {
LinkedList<Integer> stack=new LinkedList<>();
Map<Integer,Integer> map=new HashMap<>();
int[] res=new int[nums.length];
Arrays.fill(res,-1);
for(int i=0;i<nums.length*2;i++){
int cur=nums[i%nums.length];
while(!stack.isEmpty()&&nums[stack.peek()]<cur){
int old=stack.pop();
res[old]=cur;
}
stack.push(i%nums.length);
}
return res;
}
}
思路:
// @Title: 下一个更大元素 II (Next Greater Element II)
// @Author: qisiii
// @Date: 2024-06-24 15:37:47
// @Runtime: 45 ms
// @Memory: 44.9 MB
// @comment:
// @flag:
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res=new int[nums.length];
int n=nums.length;
for(int i=0;i<nums.length;i++){
int max=-1;
int cur=nums[i];
int j=i==n-1?0:i+1;
int time=0;
while(time<n&&nums[j]<=cur){
time++;
if(j==n-1){
j=0;
}else{
j++;
}
}
if(time<n){
max=nums[j];
}
res[i]=max;
}
return res;
}
}