首页 > 编程语言 > 详细

122-350. 两个数组的交集 II

时间:2020-12-31 11:25:25      阅读:31      评论:0      收藏:0      [点我收藏+]
给定两个数组,编写一个函数来计算它们的交集。(前面两个是我写的,后面两个抄的)
class Solution(object):

    def intersect0(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        set1 = set(nums1)
        set2 = set(nums2)
        iter_ = set1 & set2

        ret_dict1 = self.count(nums1)
        ret_dict2 = self.count(nums2)

        ret_list = []
        for item in iter_:
            if item in ret_dict1 and item in ret_dict2:
                ret_list.extend([item] * min(ret_dict1[item], ret_dict2[item]))
        return ret_list

    def count(self, nums):
        ret_dict = {}
        for item in nums:
            count = ret_dict.get(item, 0)
            ret_dict[item] = count + 1
        return ret_dict

    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        set1 = set(nums1)
        set2 = set(nums2)
        iter_ = set1 & set2

        ret_list = []
        for item in iter_:
            ret_list.extend([item]*min(nums1.count(item), nums2.count(item)))
        return ret_list

    def intersect1(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        result = []
        nums1_dict = {}
        for item in nums1:
            nums1_dict.setdefault(item, 0)
            nums1_dict[item] += 1

        for item2 in nums2:
            if nums1_dict.get(item2, 0) > 0:
                result.append(item2)
                nums1_dict[item2] -= 1
        return result

    def intersect2(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        i, j = 0, 0
        res = []
        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                res.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
        return res


if __name__ == ‘__main__‘:
    s = Solution()
    nums1 = [1, 2, 2, 1]; nums2 = [2, 2]
    # nums1 = [4, 9, 5]; nums2 = [9, 4, 9, 8, 4]
    print(s.intersect(nums1, nums2))

122-350. 两个数组的交集 II

原文:https://www.cnblogs.com/liuzhanghao/p/14214862.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!