Java 21 ms solution


  • 0
    0
    /**
     * Created by ZYC on 2017/5/15.
     */
    public class Solution {
        public int[] nextGreaterElements(int[] nums) {
            int len = nums.length;
            if (len == 0) {
                return nums;
            }
            int[] next = new int[len];
            for (int i = 0; i < len; i++) {
                next[i] = (i + 1) % len;
            }
            int max = Integer.MIN_VALUE;
            int maxPos = -1;
            for (int i = 0; i < len; i++) {
                if (nums[i] > max) {
                    max = nums[i];
                    maxPos = i;
                }
            }
            int[] result = new int[len];
            result[maxPos] = -1;
            for (int i = (maxPos + len - 1) % len; i != maxPos; i = (i + len - 1) % len) {
                int nextPos = next[i];
                while (nums[nextPos] < nums[i]) {
                    nextPos = next[nextPos];
                }
                if (nums[nextPos] == nums[i]) {
                    result[i] = result[nextPos];
                    next[i] = next[nextPos];
                } else {
                    result[i] = nums[nextPos];
                    next[i] = nextPos;
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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