7.Next Greater Element II
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.Solution I: (Brute Force)
class Solution
{
public:
vector<int> nextGreaterElements(vector<int> &nums)
{
vector<int> res;
int n = nums.size();
vector<int> v(2 * n);
for (int i = 0; i < 2 * n; i++)
{
v[i] = nums[i % n];
}
for (int i = 0; i < n; i++)
{
int max = -1;
for (int j = i+1; j < v.size(); j++)
{
if (v[j] > nums[i])
{
max = v[j];
break;
}
}
res.push_back(max);
}
return res;
}
};Solution II: (Using stack)
Last updated