如何比较两组?

How to compare two sets to each other?

我目前正在尝试解决 leetcode 上的“问题 349 - 两个数组的交集”,并试图 return 一个数组的交集。我的目标是制作两个单独的集合来接收每个数组的值,因为我需要唯一的值。

我很困惑我现在应该如何遍历这两个集合以 return 匹配的元素和 return 匹配的元素。这是我的代码,我遇到了一个问题,它告诉我 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

使用集合 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 接受一个可迭代对象作为参数,因此使用列表就可以了。

您可以使用 &(设置交集)运算符。

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

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

>> 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))