503. Next Greater Element II
Posted lychnis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
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)
以上是关于503. Next Greater Element II的主要内容,如果未能解决你的问题,请参考以下文章
leetcode496 - Next Greater Element I - easy && leetcode503 - Next Greater Element II - medi
[栈] leetcode 503 Next Greater Element II