声明:
今天是第79道题。给定两个数组,编写一个函数来计算它们的交集。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除
(手动比心ღ( ´・ᴗ・` ))
正文
题目:给定两个数组,编写一个函数来计算它们的交集。
示例 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个集合不重合元素的功能,先找出不一样的,再用nums1减去不同的,然后就可以返回相同的了,注意返回时把set转为list,代码如下。
执行用时: 28 ms, 在Intersection of Two Arrays的Python提交中击败了99.86% 的用户
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
final = set(nums1).difference(set(nums2))
return list(set(nums1)-final)
# 更加pythonic的做法:return list(set(nums1) & set(nums2))
解法2。常规做法,遍历nums1中的每个元素,如果也在nums2中就放到1个list中,最后返回时用set对这个list去重然后再转为list即可,代码如下。
执行用时: 48 ms, 在Intersection of Two Arrays的Python提交中击败了36.14% 的用户
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []
for i in nums1:
if i in nums2:
res.append(i)
# 以上更加pythonic的做法是:
# res = [i for i in nums1 if i in nums2]
return list(set(res))
结尾
解法1&解法2:原创