leetcode503. Next Greater Element II

題目要求

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.java

Example 1: 算法

Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.數組

Note:The length of given array won't exceed 10000.this

假設如今在有一個循環數組,即數組的第一個元素是數組最後一個元素的下一個元素。如今要求生成一個新的數組,該新的數組的每個元素分別表示原數組中第一個大於該下標元素的值。code

思路和代碼

若是該數組不是一個循環數組,則經過棧的一輪遍歷就能夠將全部元素的下一個更大的元素找出來。找出來的方法即爲一旦遇到一個元素大於棧頂的元素,就將棧中的元素退出,由於當前元素就是棧頂元素下一個更大的元素。ci

可是由於該數組是一個循環數組,因此只須要再遍歷一輪數組,這一輪無需將元素入棧,只須要不斷的將小於當前元素的棧頂元素彈出便可。這裏要注意,數組中的最大元素在這種算法下將永遠不會彈出,所以須要將結果集中的默認值設爲-1.element

public int[] nextGreaterElements(int[] nums) {
        int n = nums.length, next[] = new int[n];
        Arrays.fill(next, -1);
        Stack<Integer> stack = new Stack<>(); // index stack
        for (int i = 0; i < n * 2; i++) {
            int num = nums[i % n]; 
            while (!stack.isEmpty() && nums[stack.peek()] < num)
                next[stack.pop()] = num;
            if (i < n) stack.push(i);
        }   
        return next;
    }
相關文章
相關標籤/搜索