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; }
相关文章
相关标签/搜索