python 两个数组的交集 intersection of two arrays

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

例子:

给定 num1= [1, 2, 2, 1], nums2 = [2, 2], 返回 [2].

提示:

  • 每个在结果中的元素必定是唯一的。
  • 我们可以不考虑输出结果的顺序。
class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        setNums1 = set(nums1)
        setNums2 = set(nums2)
        
        result = []
        for x in setNums2:
            if x in setNums1:
                result.append(x)
        return result

用set来把list的重复元素过滤掉,然后判断是否存在,把结果保存起来
http://www.waitingfy.com/archives/3724

3724

Leave a Reply

Name and Email Address are required fields.
Your email will not be published or shared with third parties.