496. Next Greater Element I
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.
解析:方法一:这道题给了我们一个数组,又给了该数组的一个子集合,让我们求集合中每个数字在原数组中右边第一个较大的数字。可以先采用暴力搜索,遍历子集合中的每一个数字,然后在原数组中找到这个数字,然后向右遍历,找到第一个大于该数字的数即可,代码如下:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
vector<int> res(findNums.size());
for (int i = 0; i < findNums.size(); ++i) {
int j = 0, k = 0;
for (; j < nums.size(); ++j) {
if (nums[j] == findNums[i])
break;
}
for (k = j + 1; k < nums.size(); ++k) {
if (nums[k] > nums[j]) {
res[i] = nums[k];
break;
}
}
if (k == nums.size())
res[i] = -1;
}
return res;
}
};
方法二: 上面的方法稍做优化,用Map表先来建立每个数字和其坐标位置之间的映射,那么在遍历子集合中的数字时,就能直接定位到该数字在原数组中的位置,然后再往右边遍历寻找较大数即可:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
vector<int> res (findNums.size());
unordered_map<int, int> m;
for(int i = 0 ;i<nums.size();i++){
m[nums[i]] = i ;
}
for(int i = 0;i<findNums.size();i++){
res[i]= -1;
int start = m[findNums[i]];
for(int j = start+1;j<nums.size();j++){
if(nums[j]>nums[start]){
res[i]=nums[j];
break;
}
}
}
return res;
}
};