码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-easy-array-50. Intersection of Two Arrays II

时间:2019-06-06 15:31:21      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:运算   get   section   inter   array   solution   intersect   for   turn   

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

 

leetcode-easy-array-50. Intersection of Two Arrays II

标签:运算   get   section   inter   array   solution   intersect   for   turn   

原文地址:https://www.cnblogs.com/rosyYY/p/10985062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!