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中找到相应的位置,然后从nums2中找到比相应数字大的数据存到结果数组中。
解题代码:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
vector<int> result;
int size1 = findNums.size();
int size2 = nums.size();
for(int i = 0;i<size1;i++)
{
int j = 0;
for(;j<size2;j++)
{
if(nums[j] == findNums[i])
{
break;
}
}
j = j+1;
int k = 0;
while(j<size2 && k ==0)
{
if(nums[j] > findNums[i])
{
k = 1;
}
j++;
}
if(k == 1)
{
result.push_back(nums[j-1]);
}
else
result.push_back(-1);
}
return result;
}
};