Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Note:
Follow up:
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
C = collections.Counter
return list((C(nums1) & C(nums2)).elements()) #&代表求交集运算
import collections
nums1=[3,1,4,4,2,2,]
nums2=[3,3,5,6,2,2,2]
C = collections.Counter
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
maps={}
for n in nums1:
if n in maps:
maps[n]+=1
else:
maps[n]=1
result=[]
for i in range(len(nums2)):
if nums2[i] in maps and maps[nums2[i]]>0:#>0其实是在取交集
result.append(nums2[i])
maps[nums2[i]]-=1
return result
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1=set(nums1)
nums2=set(nums2)
return list(nums1&nums2)
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
maps=[]
for n in nums1:
if n not in maps:
maps.append(n)
result=[]
for i in range(len(nums2)):
if nums2[i] in maps and nums2[i] not in result:
result.append(nums2[i])
return result