如何比较两个集合?

cgh8pdjw  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(313)

我目前正在尝试解决leetcode上的“问题349-两个数组的交集”,并试图返回它们交集的数组。我的目标是创建两个单独的集合,它们接受每个数组的值,因为我需要唯一的值。
我不知道现在应该如何迭代这两个集合以返回匹配的元素并返回它。这是我的代码,我有一个问题,它告诉我 bool object is not iterable 这是有道理的:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        set1 = set()
        set2 = set()
        newList = []
        for i in nums1:
            set1.add(i)
        for j in nums2:
            set2.add(j)
        for i in set1 and j in set2:
            if (set1(i) == set2(j)):
                newList.append[i]
        return newList
bnl4lu3b

bnl4lu3b1#

你可以使用 & (设置交点)操作符。

>> s1 = {1, 2, 3}
>> s2 = {2, 3, 4}
>> s1 & s2
{2, 3}

或者使用非运算符方法 intersection 与运算符相反,它也将iterable(不一定是集合)作为其参数。

>> s1.intersection(s2)
{2, 3}
>> s1.intersection([2, 3, 4])
{2, 3}

如有必要,转换为列表。
就你而言:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))
sigwle7e

sigwle7e2#

使用一套 intersection 方法。

def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:
    set1 = set(nums1)
    set2 = set(nums2)
    result = set1.intersection(set2)
    return list(result)

这可以缩短为

def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:
    return list(set(nums1).intersection(nums2))

不需要手动迭代列表来创建集合。 set 接受iterable作为参数,因此使用列表是可以的。

相关问题