您当前的位置: 首页 > 

IT之一小佬

暂无认证

  • 0浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

两个数组的交集

IT之一小佬 发布时间:2021-05-15 22:56:37 ,浏览量:0

两个数组的交集

给定两个数组,编写一个函数来计算它们的交集。

示例 1:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]

示例代码1:

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        a = []
        for i in nums1:
            if i in nums2:
                a.append(i)
        return list(set(a))

示例代码2:

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        def set_a(set1, set2):
            return [i for i in set1 if i in set2]
        
        set1 = set(nums1)
        set2 = set(nums2)
        if len(set1) < len(set2):
            return set_a(set1, set2)
        else:
            return set_a(set2, set1)

示例代码3:

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        set1 = set(nums1)
        set2 = set(nums2)
        return self.set_intersection(set1, set2)
        
    def set_intersection(self, set1, set2):
        if len(set1) < len(set2):
            return [i for i in set1 if i in set2]
        return [i for i in set2 if i in set1]

示例代码4:

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        len1, len2 = len(nums1), len(nums2)
        list1 = ["x"]
        index1 = index2 = 0
        while index1 < len1 and index2 < len2:
            num1 = nums1[index1]
            num2 = nums2[index2]
            if num1 == num2:
                if num1 != list1[-1]:
                    list1.append(num1)
                index1 += 1
                index2 += 1
            elif num1 < num2:
                index1 += 1
            else:
                index2 += 1
        return list1[1:]

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0402s