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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
在一个循环列表中,找到每个数字中,下一个比他大的数字
方法一:
用一个栈,一个队列。栈放置一个降序的子集,队列放一个升序的子集。
class Solution {
public int[] nextGreaterElements(int[] nums) {
int []ans = new int[nums.length];
// 保存降序子集
Stack<Integer> num = new Stack<>();
Stack<Integer> index = new Stack<>();
// 保存升序子集
Queue<Integer> upNum = new ArrayDeque<>();
int maxValue = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
if (num.empty()) {
num.push(nums[i]);
index.push(i);
upNum.add(nums[i]);
maxValue = nums[i];
} else {
while (!num.empty() && nums[i] > num.peek()) {
ans[index.peek()] = nums[i];
num.pop();
index.pop();
}
num.push(nums[i]);
index.push(i);
if (nums[i] > maxValue) {
upNum.add(nums[i]);
maxValue = nums[i];
}
}
}
// 降序中,如果还有没有标记的,就再从升序队列中找到。
while (!num.empty()) {
int curNume = num.pop();
int curIndex = index.pop();
if (curNume == maxValue) {
ans[curIndex] = -1;
continue;
}
while (!upNum.isEmpty()) {
if (curNume < upNum.peek()) {
ans[curIndex] = upNum.peek();
break;
} else {
upNum.poll();
}
}
}
return ans;
}
}
方法二:
循环是2倍的数组长度,用栈来保存降序序列的index。
class Solution {
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;
// 遍历第一轮,把没有找到比他大的数字放起来,所以stack里面的数据都是降序的。然后再进行第二轮遍历
if (i < n) stack.push(i);
}
return next;
}
}