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.
题意:给出一个循环数组,找出每个元素的下一个大于它的值,若不存在,则记为-1。
方法一:观测到数据范围并不大,暴力破解:
class Solution{
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int len=nums.size();
for(int i=0; i<len; i++) {
nums.push_back(nums[i]);
}
vector<int>vec(len,-1);
for(int i=0; i<len; i++) {
for(int j=i+1; j<i+len; j++){
if(nums[j]>nums[i]) {
vec[i]=nums[j];
break;
}
}
}
return vec;
}
};
方法二:维护一个栈,栈中的元素都未找到下一个大于它的值。当栈为空或者当前栈顶元素大于遍历到的nums[i]时,nums[i]进栈,表示nums[i]还未找到下一个大于它的值。当栈顶元素小于nums[i]时,则有栈顶元素找到下一个较大的元素,将其出栈并记录。nums数组为循环数组,可以将其复制一遍,再加入数组。
class Solution{
public:
vector<int> nextGreaterElements(vector<int>& nums){
stack<int>st;
int len=nums.size();
vector<int>vec(len,-1);
for(int i=0; i<len*2; i++) {
int j=i%len;
while(!st.empty()&&nums[st.top()]<nums[j]) {
//栈顶元素找到下一个大于它的值
vec[st.top()]=nums[j];
st.pop();
}
if(i<len) //当前元素入栈
st.push(i);
}
return vec;
}
};