[leetcode]503. Next Greater Element II
Analysis
电脑坏了—— [心塞!!]
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.
Implement
方法一:(暴力)
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int len = nums.size();
vector<int> res(len, -1);
for(int i=0; i<len; i++){
for(int j=i+1; j<len+i; j++){
if(nums[j%len] > nums[i]){
res[i] = nums[j%len];
break;
}
}
}
return res;
}
};
方法二:(stack)
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int len = nums.size();
vector<int> res(len, -1);
stack<int> nums1;
for(int i=0; i<2*len; i++){
int num = nums[i%len];
while(!nums1.empty() && nums[nums1.top()] < num){
res[nums1.top()] = num;
nums1.pop();
}
if(i<len)
nums1.push(i);
}
return res;
}
};