Description
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.
Solution
Stack, time O(n), space O(n)
这道题蛮有意思的,如果用array去做需要O(n ^ 2)的时间,但是用stack做又没什么头绪,后来发现可以换一种思路去用stack。往常某元素x入栈的时候,x可能成为栈中元素的next greater value,但是我们换一个思路,栈中元素储存next greater value candidates,某元素x入栈的时候则在栈中寻找它的next greater value。
由于是cycler array,我们需要将array中元素逆序入栈,然后逆序遍历array,这样遍历到元素x的时候,能够保证x的cycler next values都在栈中。
class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack<Integer> stack = new Stack<>();
int n = nums.length;
int[] res = new int[n];
Arrays.fill(res, -1);
for (int i = n - 1; i >= 0; --i) {
stack.push(nums[i]);
}
for (int i = n - 1; i >= 0; --i) {
while (!stack.empty() && stack.peek() <= nums[i]) {
// pop directly because nums[i] is better than stack.peek()
// "greater" means nums[i] is larger and i is smaller
stack.pop();
}
if (!stack.empty()) {
res[i] = stack.peek();
}
stack.push(nums[i]);
}
return res;
}
}