三种方法
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
# 1.先来个暴力法
res = [0 for i in range(len(nums1))]
for i in range(len(nums1)):
j = nums2.index(nums1[i])
k = j + 1
while k < len(nums2) and nums2[k] <= nums1[i]:
k += 1
res[i] = nums2[k] if k < len(nums2) else -1
# return res
# 2.单调栈:一但要求下一个更大的元素,就是用单调栈解
# 单调栈分为两种,一种从后往前遍历,一种从前往后遍历
# 2.1 从后往前
res = {} # 用哈希表存储
stack = []
for num in reversed(nums2):
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]
# 2.2 从前往后
res = {}
stack = []
for num in nums2:
while stack and num > stack[-1]:
temp = stack.pop()
res[temp] = num
stack.append(num)
# 循环结束,如果stack中还有元素,则为单调递增的,没有下一个最大元素
# 2.1则少了这一步
if stack:
for i in stack:
res[i] = -1
return [res[num] for num in nums1]