Java: Easy to understand & concise solution


  • 1
    M
    public class Solution {
    public int[] nextGreaterElements(int[] nums) {    
        if(nums == null || nums.length == 0) return new int[0];
        int n = nums.length;
        int[] result = new int[n];
        for(int i = 0; i < n; ++i){
            int j = (i + 1) % n;
            for(; j != n && j != i; ){
                if(nums[j] > nums[i]) break;
                j = (j + 1) % n;
            }
            if(j == i) result[i] = -1;
            else result[i] = nums[j];
        }
        return result;
    }
    }

Log in to reply
 

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