Java 20ms beat 99.96%


  • 1
    B
    public class Solution {
        public int[] nextGreaterElements(int[] nums) {
            int n = nums.length;
            int[] res = new int[n];
            if(n==0) return res;
            int max = nums[0],index = 0;
            for(int i=0;i<n;i++){
                if(nums[i]>max){
                    res[i-1] = i;
                    res[index] = i;
                    max = nums[i];
                    index = i;
                }
            }
            res[index] = -1;
            for(int i=index-1;i>index-n;i--){
                int real = (i+n)%n;
                if(res[real]!=0) continue;
                res[real] = real==n-1?0:real+1;
                while(res[real]!=-1&&nums[real]>=nums[res[real]]){
                    res[real] = res[res[real]];
                }
            }
            for(int i=0;i<n;i++){
                if(res[i]!=-1){
                  res[i] = nums[res[i]]; 
                }
            }
            return res;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.