class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
if not nums1 or not nums2: #有一个为空
return []
stack = [nums2[0]] #栈初始
hash = {} #hash表
for num in nums2[1:]:
while len(stack) > 0 and num > stack[-1]:
hash[stack[-1]] = num
stack.pop()
stack.append(num)
#处理输出
res = []
for num in nums1:
if num in hash:
res.append(hash[num])
else:
res.append(-1)
return res
2021.10.26
class Solution:
def nextGreaterElement(self, nums1, nums2) :
stack = [nums2[0]]
n,m = len(nums1), len(nums2)
hash = {}
for i in range(1,m):
while len(stack) > 0 and nums2[i] > stack[-1]:
num = stack.pop()
hash[num] = nums2[i]
stack.append(nums2[i])
res = [-1]* n
for j in range(n):
if nums1[j] in hash:
res[j] = hash[nums1[j]]
return res
n, m = len(nums1), len(nums2)
hash = {} #映射nums1每个元素的<值,下标>
for i in range(n):
hash[nums1[i]] = i
res = [-1] * n
stack = [] #放的是下标
for i in range(m-1, -1, -1):
while stack and nums2[stack[-1]] < nums2[i]:
stack.pop()
if nums2[i] in hash:
index = hash[nums2[i]]
res[index] = nums2[stack[-1]] if stack else -1
stack.append(i)
return res