1. 程式人生 > >503. Next Greater Element II

503. Next Greater Element II

this int ber ava ng- 說明 emp last shm

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.

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.

我們可以使用棧來進行優化上面的算法,我們遍歷兩倍的數組然後還是坐標i對n取余,取出數字,如果此時棧不為空,且棧頂元素小於當前數字,說明當前數字就是棧頂元素的右邊第一個較大數,那麽建立二者的映射,並且去除當前棧頂元素,最後如果i小於n,則把i壓入棧。因為res的長度必須是n,超過n的部分我們只是為了給之前棧中的數字找較大值

,所以不能壓入棧,參見代碼如下:

有用hashMap 存-1的值, 用的是Arrays.fill(nums, -1)

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;
    }

  

503. Next Greater Element II