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.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
- All elements in
nums1
andnums2
are unique. - The length of both
nums1
andnums2
would not exceed 1000.
中文:
给定两个没有重复元素的数组 nums1
和 nums2
,其中nums1
是 nums2
的子集。找到 nums1
中每个元素在 nums2
中的下一个比其大的值。
nums1
中数字 x 的下一个更大元素是指 x 在 nums2
中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
示例 1:
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
示例 2:
输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于num1中的数字2,第二个数组中的下一个较大数字是3。
对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。
注意:
-
nums1
和nums2
中所有元素是唯一的。 -
nums1
和nums2
的数组大小都不超过1000。
这个要审题,这个说的是该数的右边的第一个比它更大的数,而不是比它大的数的数量。。。
于是可以用栈,同时用map计数,(unordered_map更好,原理是哈希表)
参考内容:
解法三:栈和哈希表(数字与右边更大数映射)
解题思路:
理解一:这道题要解决的问题比较简单。一,找到findNums中的数字在nums中的位置;二,寻找右边第一个更大的数字。
理解二(解法三):一,先找出在muns中每一个元素的右边更大的数字;二,判断findNums中的数字是否在nums中,然后取得相应的右边第一个更大的数字或赋值-1。思路的改变,带来解法的改变。
要点:如何利用已有的数据结构,快速解决这两个问题?
(1)先找出在muns中每一个元素的右边更大的数字:哈希表 和 栈
#生长点#
---为什么用栈来做比较更快?或者为什么这里可以用上栈结构?
举个例子:1 3 8 2 4 6 9
用栈比较时:
1)1入栈,接着扫描到3,因为3比1大,所以1——>3,
2)然后1出栈,3进栈,接着扫描到8,因为8比3大,所以3——>8
3)然后3出栈,8进栈,接着扫描到2,2不大于8,2进栈,2成为新的栈顶元素
4)接着扫描到4,因为4比2大,所以2——>4,然后2出栈,此时栈顶元素为8,因4不大于8,4进栈,继续扫描
5)接着扫描到6,因为6比4大,所以4——>6,然后4出栈,此时栈顶元素为8,因6不大于8,6进栈,继续扫描
6)接着扫描到9,因为9比6大,所以6——>9,然后6出栈,此时栈顶元素为8,因9比8大,8——>9,然后8出栈,此时栈空
7)9进栈,栈只有一个元素,后面没有更大的元素了。 注:栈的特点体现在寻找 数字8 的右边第一个更大的 数字9 上面。
参考链接:https://www.cnblogs.com/paulprayer/p/10169532.html#_label3
C++ 代码:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
stack<int> s;
map<int,int> mp;
for(int i = ;i < nums.size(); i++){
while(!s.empty() && s.top() < nums[i]){
mp[s.top()] = nums[i];
s.pop();
}
s.push(nums[i]);
}
vector<int> res;
for(int i = ; i < findNums.size(); i++){
if(mp.count(findNums[i]))
res.push_back(mp[findNums[i]]);
else
res.push_back(-);
}
return res;
}
};