LeetCode:Next Greater Element II

503. Next Greater Element II

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.

 思路:首先想到最直接的思路就是依次环形搜索,时间复杂度为O(n*n)

 1 vector<int> nextGreaterElements(vector<int>& nums) 
 2 {
 3     vector<int>r;
 4     int size = nums.size();
 5     for (int i = 0; i < size; i++)
 6     {
 7         bool exist = false;
 8         for (int j = (i + 1)%size; j != i; j = (j + 1) % size)
 9         {
10             if (nums[i]<nums[j])
11             {
12                 exist = true;
13                 r.push_back(nums[j]);
14                 break;
15             }
16         }
17         if (!exist)
18             r.push_back(-1);
19     }
20     return r;
21 }

 

 

如果你有任何疑问或新的想法,欢迎在下方评论。

 

posted @ 2017-03-16 21:40  陆小风不写代码  阅读(132)  评论(0编辑  收藏  举报