349. Intersection of Two Arrays (Easy)

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

题意:保证列表中每个元素都是唯一的;利用python中列表求交集的方法;

思路:

1.遍历nums1,如果某个元素同时也存在于nums2中,则返回,并利用set()去重;

2.把列表转换为集合,利用集合操作符求出交集,然后再转换回列表类型;

# 遍历
class Solution():
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        list_a = [n for n in set(nums1) if n in nums2]
        return list_a
# 利用set数据结构的与运算
class Solution():
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
    
        return list(set(nums1) & set(nums2)) 
原文地址:https://www.cnblogs.com/yancea/p/7495318.html