mycode  77.78%

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        def deal(dic,nums):
            res = []
            for item in nums:
                if item in dic and dic[item]!=0:
                    res.append(item)
                    dic[item] -= 1
            return res
        
        dic = {}
        if len(nums1) > len(nums2): 
            for item in nums2:
                dic[item] = dic.get(item,0) + 1
            return deal(dic,nums1)
        else:
            for item in nums1:
                dic[item] = dic.get(item,0) + 1
            return deal(dic,nums2)

 

参考:

1、应用collection.Counter库,可以实现与运算

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        return list((collections.Counter(nums1) & collections.Counter(nums2)).elements())

 2、 

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        map = {}
        for i in nums1:
            map[i] = map[i]+1 if i in map else 1
        for j in nums2:
            if j in map and map[j] > 0:
                res.append(j)
                map[j] -= 1

        return res

 

相关文章:

  • 2022-12-23
  • 2021-04-12
  • 2021-10-14
  • 2021-06-03
  • 2022-12-23
  • 2021-07-07
  • 2021-10-10
猜你喜欢
  • 2021-08-15
  • 2021-10-04
  • 2021-11-29
  • 2021-07-31
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案