leetcode503—— Next Greater Element II (JAVA)

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:
this

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.spa

轉載註明出處:http://www.cnblogs.com/wdfwolf3/,謝謝。code

時間複雜度O(n),51ms。此題變成循環數來容許找nextGreaterElement,因此能夠當作數組nums後面拼接一個nums,這樣對於每一個元素它後面都有一份完整的nums,按照題1的作法處理nums,區別是這裏stack中是索引,不是值。blog

public int[] nextGreaterElement(int[] nums){
        //ans數組存放結果
        int[] ans = new int[nums.length];
     //輔助棧,存放待查找結果元素的索引,找到的當即出棧。 Stack
<Integer> stack = new Stack<>(); //第一次遍歷nums,同第一個問題,查找元素的nextGreaterElement。 for (int i = 0; i < nums.length; i++) { while(!stack.isEmpty() && nums[stack.peek()] < nums[i]){ ans[stack.peek()] = nums[i]; stack.pop(); } stack.push(i); } //第二次遍歷nums,至關於在元素的左邊查找nextGreaterElement,可是再也不入棧,由於元素在第一次遍歷時已經被遍歷過,不能再次入棧 for (int i = 0; i < nums.length; i++) { while(!stack.isEmpty() && nums[stack.peek()] < nums[i]){ ans[stack.peek()] = nums[i]; stack.pop(); } } //此時棧中存放的是沒有找到nextGreaterElement的元素,在結果中賦值-1 for (Integer i : stack){ ans[i] = -1; } return ans; }
相關文章
相關標籤/搜索