要求:
给定两个数组,写一个方法来计算它们的交集。
示例:
给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
分析:
先对两个数组由小到大排序,用两个指针index1和index2遍历两个数组,比较对应元素的大小,如果相等,则添加进result数组,如果不相等,元素小的数组指针加一,最终其中一个数组遍历结束,就停止程序。
代码:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | class Solution:def intersect(self, nums1, nums2):
 """
 :type nums1: List[int]
 :type nums2: List[int]
 :rtype: List[int]
 """
 result = []
 nums1.sort()
 nums2.sort()
 index1, index2 = 0, 0
 n1, n2 = len(nums1), len(nums2)
 
 while index1 < n1 and index2 < n2:
 if nums1[index1] == nums2[index2]:
 result.append(nums1[index1])
 index1 += 1
 index2 += 1
 elif nums1[index1] > nums2[index2]:
 index2 += 1
 else:
 index1 += 1
 return result
 
 | 
参考资料:
1、两数组的交 II https://blog.csdn.net/guoziqing506/article/details/51569488