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,其中nums1是nums2的子集。查找nums1中每个元素nums1[i]在nums中的下一个大的元素(位于nums1[i]在nums2中对应位置的右方)。如果存在,则返回下一个大的元素;如果不存在,返回-1.
Example 1:
Example
2:
实现一:
使用迭代器iterator,使用find()函数查找nums1中元素在nums2中的位置,并使用distance()函数返回位置,然后再返回位置的右边查找下一个大的元素。注:使用STL的vector时,可以利用函数 max_element,min_element,distance可以获取Vector中最大、最小值的值和位置索引,如下:
int main{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
std::vector<double>::iterator biggest = std::max_element(std::begin(v), std::end(v));
std::cout << "Max element is " << *biggest<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
return 0;
}
Code:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
int n = findNums.size();
vector<int>::iterator it;
vector<int> NGE(n);
for(int i=0; i<n; i++){
it = find(nums.begin(),nums.end(),findNums[i]);
int j = distance(nums.begin(),it)+1;
for(j; j<nums.size(); j++){
if(nums[j]>findNums[i]){
NGE[i]=nums[j];
break;
}
}
if(j==nums.size()) NGE[i]=-1;
}
return NGE;
}
};
实现二:
使用stack+unordered_map,因为nums1是nums2的子集,所以要找nums1中元素在nums2中的“下一个大的元素”,只需要对nums2中元素建立<当前元素,下一个大的元素>对应关系。使用unordered_map<int, int> m来存放对应关系,使用stack来帮助建立对应关系。m.count()返回匹配给定主键的元素的个数。Code:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
stack<int> s;
unordered_map<int, int> m;
for (int n : nums) {
while (s.size() && s.top() < n) {
m[s.top()] = n;
s.pop();
}
s.push(n);
}
vector<int> ans;
for (int n : findNums) ans.push_back(m.count(n) ? m[n] : -1);
return ans;
}
};