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.
本题是上一题的延伸,但思路不变,唯一需要注意的它是环形数组,因此需要模运算来实现数组的遍历
class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int len=nums.size(); vector<int> ans; int add; for(int i=0;i<len;i++) { int count; int temp=0; int j=i+1; for(count=0;count<len;count++) { j=j%len; if(nums[i]<nums[j]) { ans.push_back(nums[j]); break; } j++; } if(count==len) ans.push_back(-1); } return ans; } };