【英文题目】(学习英语的同时,更能理解题意哟~)
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.
【中文题目】
给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
示例 1:
输入: [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
【思路】
本题和【T25-下一个更大元素 I】基本类似,可以把数组复制一次,这样数组长度为2n,而只需计算前n个元素的greater number并返回结果即可。
暴力破解,两层循环,时间复杂度O(n^2)
使用栈,循环遍历元素e,当栈为空或者e大于栈顶元素,弹出栈顶元素,否则压栈。(栈始终维持栈顶元素到栈底元素从小到大)
【代码】
python版本
class Solution(object):
def nextGreaterElements(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if len(nums) < :
return []
ls = []
res = [-1] * len(nums)
# 第一次循环
for i,n in enumerate(nums):
while len(ls) > and nums[ls[-1]] < n:
res[ls.pop()] = n
ls.append(i)
# 第二次循环,不再添加元素
for i,n in enumerate(nums):
while len(ls) > and nums[ls[-1]] < n:
res[ls.pop()] = n
return res
C++版本
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
// 所有的结果初始化为-1
vector<int> res(nums.size(), -1);
if(nums.size() < )
return res;
stack<int> ls;
ls.push();
// 第一次循环
for(int i=; i<nums.size(); i++){
while(ls.size() > && nums[ls.top()] < nums[i]){
res[ls.top()] = nums[i];
ls.pop();
}
ls.push(i);
}
// 第二次循环,栈不再添加元素
for(int i=; i<nums.size(); i++){
while(ls.size() > && nums[ls.top()] < nums[i]){
res[ls.top()] = nums[i];
ls.pop();
}
}
return res;
}
};