给定两个没有重复元素的数组 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。
暴力法:
class Solution:
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
greater = []
for num in nums1:
greaternum = -float('inf')
stacks = nums2.copy()
while True:
nextnum = stacks.pop()
if nextnum == num: # 如果在nums2中找到num就停止迭代
break
elif nextnum >= num:# 找到nums2的num之后的第一个比num大的数
greaternum = nextnum
if num > greaternum: #没有找到就返回-1
greater.append(-1)
else:#找到了就返回这个最近的比num大的数
greater.append(greaternum)
return greater
利用单调栈和哈希表
- 首先遍历nums2,建立一个单调栈,栈顶始终存放前n位的最小元素
- 将每一个值与栈顶元素比较,如果这个值大于栈顶元素。弹出这个栈顶元素,将这个弹出的值作为键,这个当前值作为值,放在哈希表中,直到这个小于栈顶元素,就将这个值push进栈中。
- 然后,遍历nums1,如果nums1中的值在哈希表的key中,就输出value,没有就输出-1
class Solution:
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
stack = []
hashtable = {}
for num in nums2:
while stack != [] and num > stack[-1]:
hashtable[stack.pop()] = num
stack.append(num)
res = []
for num in nums1:
res.append(hashtable.get(num,-1))
return res