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:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
- 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
- 我们可以不考虑输出结果的顺序。
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1‘s size is small compared to nums2‘s size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
- 如果给定的数组已经排好序呢?你将如何优化你的算法?
- 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
- 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
Sol One
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
Sol Two:
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
版权声明:本文为kidpea_lau原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。