标签:Greater number next II element array Element Next greater
503. Next Greater Element II MediumGiven 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 { 2 public: 3 vector<int> nextGreaterElements(vector<int>& nums) { 4 vector<int> res(nums.size(),-1); 5 stack<int> s; 6 int n=nums.size(); 7 for(int i=0;i<n*2;++i) 8 { 9 int num=nums[i%n]; 10 while(!s.empty()&&nums[s.top()]<num) 11 { 12 res[s.top()]=num; 13 s.pop(); 14 } 15 if(i<nums.size())s.push(i); 16 } 17 return res; 18 } 19 };
暴力可以accept, 不过太慢. 空间O(1) 时间 O(n2)
这题使用stack结构是非常完美的, 根据数组的排放顺序, 空间O(1) ~ O(n) 时间O(n)
标签:Greater,number,next,II,element,array,Element,Next,greater 来源: https://www.cnblogs.com/lychnis/p/11299254.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。