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 Next Greater Element I的扩展,本题的数组可能包含重复元素,且是循环数组,即往右找到尾之后,可以接着从头开始找更大的数。 同样使用栈,只不过需要扫描两遍数组,且栈中保存的是元素下标,理解之后发现挺巧妙的。 比如nums = [9, 8, 7, 3, 2, 1, 6],第一遍循环之后,堆栈中从低到顶剩余的元素是9,8,7,6,此时再从头开始扫描一遍数组,9,发现栈顶是6,所以6的右边更大数是9,弹出6;栈顶是7,7的右边更大数也是9;同理8,弹栈;最后栈顶只剩9了。
代码如下:
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums)
{
int n = nums.size();
vector<int> ans(n, -1);
stack<int> idx;
for (int i = 0; i < 2 * n; ++i) {
while (!idx.empty() && nums[idx.top()] < nums[i % n]) {
ans[idx.top()] = nums[i % n];
idx.pop();
}
idx.push(i % n);
}
return ans;
}
};
本代码提交AC,用时119MS。