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:
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.
转载注明出处:http://www.cnblogs.com/wdfwolf3/,谢谢。
时间复杂度O(n),51ms。此题变成循环数组来允许查找nextGreaterElement,所以可以看成数组nums后面拼接一个nums,这样对于每个元素它后面都有一份完整的nums,按照题1的做法处理nums,区别是这里stack中是索引,不是值。
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; }