难度: Easy
原题连接
内容描述
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:
Each element in the result must be unique.
The result can be in any order.
思路 1 - 时间复杂度: O(m * n)- 空间复杂度: O(1)******
时间就看python set intersection的时间了,平均O(min(m, n)),最坏O(m * n)
Python一句话作弊,beats 82.08%
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1).intersection(nums2))
思路 2 - 时间复杂度: O(m + n)- 空间复杂度: O(m)******
Counter, beats 82.08%
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
lookup = collections.Counter(nums1)
res = set()
for num in nums2:
if num in lookup:
res.add(num)
return list(res)