python-leetcode-496. 下一個更大元素 I

給定兩個沒有重複元素的數組 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每個元素在 nums2 中的下一個比其大的值。

nums1 中數字 x 的下一個更大元素是指 x 在 nums2 中對應位置的右邊的第一個比 x 大的元素。如果不存在,對應位置輸出-1。

示例 1:

輸入: nums1 = [4,1,2], nums2 = [1,3,4,2].
輸出: [-1,3,-1]
解釋:
對於num1中的數字4,你無法在第二個數組中找到下一個更大的數字,因此輸出 -1。
對於num1中的數字1,第二個數組中數字1右邊的下一個較大數字是 3。
對於num1中的數字2,第二個數組中沒有下一個更大的數字,因此輸出 -1。

解法一:

class Solution(object):
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        stack, hash = [], {}
        for n in nums2:
            while stack and stack[-1] < n:
                hash[stack.pop()] = n
            stack.append(n)
        
        return [hash.get(x, -1) for x in nums1]

解法二:

class Solution:
    def nextGreaterElement(self, nums1, nums2):
        stack, hash = [], {}
        for n in nums2:
            while stack and stack[-1] < n:
                hash[stack.pop()] = n
            stack.append(n)
        
        return [hash.get(x, -1) for x in nums1]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章