# 保持一个降序的站,每次来新的元素,从栈的右端排出比当前元素小的元素,每次排出时,判断排出的数是否是nums1中的 classSolution(object): defnextGreaterElement(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ ans = [-1for i inrange(len(nums1))] stack = [] for i in nums2: ifnot stack: stack.append(i) else: if stack[-1] >= i: stack.append(i) continue else: while stack and stack[-1] < i: out = stack.pop() if out in nums1: ans[nums1.index(out)] = i stack.append(i) return ans
classSolution(object): defnextGreaterElement(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ dic = {} stack = [] for i in nums2: ifnot stack: stack.append(i) else: if stack[-1] >= i: stack.append(i) continue else: while stack and stack[-1] < i: dic[stack.pop()] = i stack.append(i) return [dic[i] if i in dic.keys() else -1for i in nums1]