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的子集。在nums2中找到nums1中所有元素的对应的the next greater number,the next greater number是nums1中的数x在nums2中x后面的第一个大于x的数,如果没有这个数,输出-1
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:
1、All elements in nums1 and nums2 are unique.
2、The length of both nums1 and nums2 would not exceed 1000.
Solution:
Python
class Solution:
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dict0 = {} #dict0用来存储nums2中每个元素对应的the next greater number,没有的就不管了
stack = [] #栈用来存储还没找到the next greater number的元素
for i in nums2:
while stack and stack[-1] < i: #为stack中元素寻找第一个大于它的元素,找到就加入到dict0中,没找到就仍然存放在stack中
dict0[stack.pop()] = i
stack.append(i) #将每个元素都遍历到
output = []
for j in nums1: #遍历nums1中元素,根据dict0找它对应的the next greater number ,没有就默认为-1
output.append(dict0.get(j,-1))
return output
C++
#include <stack>
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
stack<int> stk; #栈
unordered_map<int,int> Map; #hash表
for (int i : nums){
while(!stk.empty() && stk.top() < i){
Map[stk.top()] = i;
stk.pop();
}
stk.push(i);
}
vector<int> output;
for (int j: findNums){
output.push_back(Map.count(j) ? Map[j] : -1); #返回匹配护肩元素的个数,就是查看有没有这个元素,没有就是0,那么就在output末尾加入-1,有就是true
}
return output;
}
};