Problem Solution Record: Simple Application of Hash Table --- 2540. Minimum Common Value

Given two arrays of integers  nums1and  nums2 they are sorted in non-descending order, please return the smallest common integer of the two arrays  . If the two array sums  nums1have  nums2 no common integers, please return them  -1 .

 An integer is array  and  common if it occurs at least once in both arrays  .nums1nums2 

Example 1:

Input: nums1 = [1,2,3], nums2 = [2,4]
 Output: 2
 Explanation: The smallest common element of both arrays is 2, so we return 2.

Example 2:

Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5]
 Output: 2
 Explanation: The common elements in the two arrays are 2 and 3, 2 is the smaller value, so return 2 .

Idea: Merge two lists, count with a hash table, and output the minimum common solution

class Solution:
    def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
        nums1 = list(set(nums1))
        nums2 = list(set(nums2))
        num = nums1 + nums2
        # print(num)
        nums = Counter(num)
        ans = []
        for k , v in nums.items():
            if v >= 2:
                ans.append(k)
        return min(ans) if ans else -1
        # print(ans)
        # return min(ans)
        # return min(ans) if value == 2 else -1

Guess you like

Origin blog.csdn.net/weixin_45314061/article/details/131815193