开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第7天,点击查看活动详情
496.下一个更大元素
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/ne…
给你两个 没有重复元素 的数组 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 。
提示:
1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 104 nums1和nums2中所有整数 互不相同 nums1 中的所有整数同样出现在 nums2 中
进阶:
你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗?
解法
-
方法1-暴力遍历法, 从第二个数组中找到该元素,遍历后面的元素,进行比较
-
python
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
# bf
res = []
n1 = len(nums1)
n2 = len(nums2)
for i in range(n1):
num1 = nums1[i]
index = nums2.index(num1)
flag = False
for j in range(index+1, n2):
num2 = nums2[j]
if num1 < num2:
res.append(num2)
flag = True
break
if flag == False:
res.append(-1)
return res
- c++
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size();
int n = nums2.size();
vector <int> res(m);
for(int i=0; i<m; i++)
{
int j = 0;
while(j<n && nums2[j] != nums1[i])
{
j++;
}
int k = j+1;
while(k<n && nums2[k] < nums2[j])
{
++k;
}
res[i] = k <n ? nums2[k] : -1;
}
return res;
}
}
方法2:对第二个数组求单调栈,然后将第二个的元素关系存到哈希表中,便于第一个数组元素查询
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stack = []
res = {}
for num in nums2[::-1]: # 倒序便于比较左边元素与右边元素的关系
while stack and num >= stack[-1]:
stack.pop()
res[num] = stack[-1] if stack else -1
stack.append(num)
return [res[num] for num in nums1]
- c++
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> hashmap;
stack<int> st;
for(int i=nums2.size()-1; i>=0; i--)
{
int num = nums2[i];
while(!st.empty() && num >= st.top())
{
st.pop();
}
hashmap[num] = st.empty() ? -1:st.top();
st.push(num);
}
vector <int> res(nums1.size());
for(int i=0; i<nums1.size(); i++)
{
res[i] = hashmap[nums1[i]];
}
return res;
}
};
复杂度分析
- 时间复杂度:O(mn) O(m+n)
- 空间复杂度:O(1) O(n)