Given two arrays, write a function to compute their intersection.
给定两个数组,编写一个函数来计算它们的交集。
EX1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
EX2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Follow up:
If two arrays 's numbers arent too big, and for the big size of arrays, there is no doubt that the idea of #COUNTING-SORT will preform really well.
毫无疑问,如果对于数字较小,而规格大的数组,用#COUNTING-SORT类似的方法是可以表现得非常棒!
Here is the code:
class Solution(object):
def intersect(self, nums1, nums2):
k=10
C=[]
B=[]
for i in range(k):
C.append(0)
for j in range(len(nums1)):
C[nums1[j]-1]=C[nums1[j]-1]+1
for j in range(len(nums2)):
if C[nums2[j]-1]>0:
B.append(nums2[j])
C[nums2[j]-1]=C[nums2[j]-1]-1
return B
But when the number is bigger than 10**3, it becomes really too big to run.
Here s the general solution.
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
record, result = {}, []
for num in nums1:
record[num] = record.get(num, 0) + 1
for num in nums2:
if num in record and record[num]:
result.append(num)
record[num] -= 1
return result