题目来源LeetCode
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.
解题思路:将数组复制两遍来进行circular,然后再进行比较找出下一个最大元素,具体代码如下:
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
vector<int>double_nums;
vector<int>results;
int l = nums.size();
for(int i = 0; i < l; i++){
double_nums.push_back(nums[i]);
}
for(int i = 0; i < l; i++){
double_nums.push_back(nums[i]);
}
for(int i = 0; i < l; i++){
for(int j = i; j <= i+l; j++){
if(double_nums[i] < double_nums[j]){
results.push_back(double_nums[j]);
break;
}
else if(j == i+l && double_nums[i] >= double_nums[j]){
results.push_back(-1);
break;
}
}
}
return results;
}
};