LeetCode 496. Next Greater Element I 单调栈
The next greater element of some element x
in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1
and nums2
, where nums1
is a subset of nums2
.
For each \(0 <= i < nums1.length\), find the index \(j\) such that \(nums1[i] == nums2[j]\) and determine the next greater element of \(nums2[j]\) in nums2. If there is no next greater element, then the answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.
Solution
利用单调栈 \(stack\), 如果栈顶元素 \(stack[-1]<nums2[i]\),说明此时可以存在 \(stack[-1]\rightarrow nums2[i]\) 的映射,直到这个条件不满足。所以最后存留在 \(stack\) 里面的都是无法配对的,此时赋予 \(-1\)
点击查看代码
class Solution(object):
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
l2 = len(nums2)
l1 = len(nums1)
mp = {}
ans = []
stack = []
for i in range(l2):
while stack and stack[-1]<nums2[i]:
mp[stack[-1]] = nums2[i]
stack.pop()
stack.append(nums2[i])
for ele in stack:
mp[ele] = -1
for i in range(l1):
ans.append(mp[nums1[i]])
return ans