LeetCode496. 下一个更大元素 I
给你两个 没有重复元素 的数组 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 <= 10000 <= nums1[i], nums2[i] <= 104nums1和nums2中所有整数 互不相同nums1中的所有整数同样出现在nums2中
**进阶:**你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗?
题解:
使用单调栈进行求解:
Java代码实现:
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int[] res = new int[m];
//定义一个单调栈
Stack<Integer> stack = new Stack<>();
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int val = nums2[i];
while (!stack.isEmpty() && stack.peek() < val) {
map.put(stack.pop(),val);
}
stack.push(val);
}
for (int i = 0; i < m; i++) {
if (map.containsKey(nums1[i])) {
res[i] = map.get(nums1[i]);
}else {
res[i] = -1;
}
}
return res;
}
}
Python代码实现:
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
map = {}
stack = []
ans = []
# 遍历nums2集合,将存在下一个更大元素的结果保存在map字典中
for val in nums2:
while len(stack) > 0 and stack[len(stack) - 1] < val:
map[stack.pop()] = val
stack.append(val)
# 遍历nums1,如果字典map中存在结果,直接获取,放入结果集中,如果不存在,则说明不存在,放入-1
for val in nums1:
if val in map:
ans.append(map[val])
else:
ans.append(-1)
return ans
该博客介绍了如何利用单调栈解决LeetCode中的第496题,即寻找给定数组中每个元素在另一个数组中的下一个更大元素。博主提供了Java和Python两种语言的代码实现,并讨论了O(nums1.length+nums2.length)的时间复杂度解决方案。
1183

被折叠的 条评论
为什么被折叠?



