Given a looping array (the element next to the last element is the first element of the array), output the next larger element of each element. The next greater element of number x is the first greater number after this number in array traversal order, which means you should loop through it to search for its next greater number. If not present, output -1.
Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The next greater number of the first 1 is 2; the
number 2 cannot find the next greater number;
The next largest number of the second 1 needs to be searched in a loop, and the result is also 2.
Note: The length of the input array will not exceed 10000.
See: https://leetcode.com/problems/next-greater-element-ii/description/
C++:
class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int n=nums.size(); vector<int> res(n,-1); for(int i=0;i<n;++i) { for(int j=i+1;j<i+n;++j) { if(nums[j%n]>nums[i]) { res[i]=nums[j%n]; break; } } } return res; } };
Reference: http://www.cnblogs.com/grandyang/p/6442861.html