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.
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.
【题解C++】
先上个暴力解法吧~思路大概是这样:首先看清题意,不是同一位置右边的第一个最大值,而是同一个值右边的最大值!既然是靠值来联系两个数组,那第一个就会想到哈希表啦。先遍历大的数组,找到每个值对应的右边第一个最大值,将二者一个作为键一个作为值。最后再遍历第一个数组,push_back。
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int i,j,hash[100000];
vector<int> out;
//建立映射表
for(i=0;i<nums2.size();i++)
{
//当前值
int tmp = nums2[i];
for(j=i+1;j<nums2.size();j++)
{
//如果右边有比当前值大的,存入哈希表
if(nums2[j]>tmp)
{
hash[tmp] = nums2[j];
break;
}
}
//否则将-1存入哈希表
if(j==nums2.size())
hash[tmp] = -1;
}
for(i=0;i<nums1.size();i++)
out.push_back(hash[nums1[i]]);
return out;
}
};
接下来优化一下~既然是栈的合集,那就用栈来实现8!
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> out;
stack<int> st;
map<int,int> mp;
//倒着遍历大数组
for(int i=nums2.size()-1;i>=0;i--)
{
//当前数组值
int now = nums2[i];
//只要栈不为空&&栈顶值不大于当前值,pop以寻找更大的值
while(!st.empty()&&st.top()<=now)
st.pop();
//如果栈为空,说明没找到比当前值更大的,赋值为-1,否则赋值为栈顶值
mp[now] = st.empty()?-1:st.top();
//入栈
st.push(now);
}
for(int i=0;i<nums1.size();i++)
out.push_back(mp[nums1[i]]);
return out;
}
};
【解题Python】
Python用的暴力,思路和C++也是一样的。
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
st = []
for i in nums1:
index = nums2.index(i)
flag = 0
for j in nums2[index:]:
if j>i:
st.append(j)
flag = 1
break
if not flag:
st.append(-1)
return st