You are given two arrays (without duplicates) nums1
and nums2
where nums1
’s
elements are subset of nums2
. Find all the next greater numbers for nums1
's
elements in the corresponding places of nums2
.
The Next Greater Number of a number x in nums1
is
the first greater number to its right in nums2
. If it does not exist, output -1 for this
number.
重点在于要确定nums1中每个元素在nums2中的位置,然后从所在位置开始向后扫描,找得到即放入新vector中,找不到把-1放入vector中。
返回结果的vector。
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
vector<int> a;
int j,k;
for(int i = 0;i < findNums.size();i++)
{
for(k = 0;k < nums.size();k++)
{
if(findNums[i] == nums[k])
break;
}
for(j = k;j < nums.size();j++)
{
if(nums[j] > findNums[i])
{
a.push_back(nums[j]);
break;
}
}
if(j == nums.size())
a.push_back(-1);
}
return a;
}
};