两个数组的交集
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
.输出结果中的每个元素一定是唯一的。
.我们可以不考虑输出结果的顺序。
代码
第一版
**思路 **
1. 由于输出结果中的每个元素一定是唯一的,首先选择一个数组变成set(自带去重功能)
2.然后 判断其中的元素是否在另外一个数组中
3.最后将在两个数组中的元素放入到list 中
// An highlighted block
def intersection(self, nums1, nums2):
tmp=[ x for x in set(nums1) if x in nums2]
return tmp
第二版
**思路 **
1.利用set去重的功能,然后利用与的位运算符号& 求并集即可
*按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 (a & b) 输出结果 12 ,二进制解释: 0000 1100
// An highlighted block
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1=set(nums1)
set2=set(nums2)
c=set1&set2
return list(c)
第三版
将第二版精简后的代码
// An highlighted block
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1)&set(nums2))