题目描述:
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.
题目大意:
给定两个数组,编写函数计算它们的交集。
测试用例如题目描述。
注意:
- 结果中的每个元素一定是唯一的。
- 结果可以采用任意顺序。
解题思路:
利用set数据结构的与运算
Python代码:
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
另一种解法:
Python代码:
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
ans = []
for x in nums2:
if x in set1:
ans += x,
set1.remove(x)
return ans
本文链接:https://bookshadow.com/weblog/2016/05/18/leetcode-intersection-of-two-arrays/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。
如果这篇博客对你有帮助,请支持书影博客
你的捐赠将用于服务器与域名费用,帮助免费技术内容持续更新。
支付宝
微信
建议金额:¥5 / ¥10 / ¥20 / ¥50(扫码后自行输入)
ans.append(x)