503. Next Greater Element II
相关问题:496. Next Greater Element I
问题:
给定数组num,对于每个元素求下一个更大的元素。
下一个的定义:右边 且 若到末尾元素,循环从index=0开始继续向右。
Example 1: Input: nums = [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. Example 2: Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4] Constraints: 1 <= nums.length <= 10^4 -10^9 <= nums[i] <= 10^9
解法:
这里,注意处理两题的区别:
next->支持循环,再从index=0的元素开始
我们可知,最多将元素组再向后续一轮即可,
即原size*2。
那么对于元素的访问,可使用mod运算得到:
nums[x]->nums[x%size]
代码参考:
1 class Solution { 2 public: 3 vector<int> nextGreaterElements(vector<int>& nums) { 4 int N=nums.size(); 5 vector<int> res(N,-1); 6 stack<pair<int,int>> s; 7 for(int n=0; n<2*N; n++) { 8 while(!s.empty() && s.top().first<nums[n%N]) { 9 res[s.top().second]=nums[n%N]; 10 s.pop(); 11 } 12 s.push({nums[n%N],n%N}); 13 } 14 return res; 15 } 16 };
⚠️ 注意:这里stack中保存的元素为 pair:
{num_value, index}