huimeich / leetcode-solution

0 stars 0 forks source link

496. Next Greater Element I #266

Open huimeich opened 4 years ago

huimeich commented 4 years ago

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

huimeich commented 4 years ago
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
    stack = []
    dic = {}
    for n in nums2:
        if not stack:
            stack.append(n)
            continue
        while stack and stack[-1] < n:
            tmp = stack.pop()
            dic[tmp] = n
        stack.append(n)
    while stack:
        tmp = stack.pop()
        dic[tmp] = -1
    ans = []
    for n in nums1:
        ans.append(dic[n])
    return ans