给定两个数组,编写一个函数来计算它们的交集。
/*** 哈希表* 时间复杂度:O(m+n)* 空间复杂度:O(min(m,n))*/var intersect1 = function (nums1, nums2) {const map = {}const res = []for (const n of nums1) {map[n] = (map[n] || 0) + 1}for (const n of nums2) {if (map[n]) {map[n]--res.push(n)}}return res}
/*** 排序、快慢指针* 时间复杂度:O(mlogm+nlogn)* 空间复杂度:O(logm+logn)*/var intersect = function (nums1, nums2) {nums1.sort((x, y) => x - y)nums2.sort((x, y) => x - y)const len1 = nums1.lengthconst len2 = nums2.lengthconst res = []let index1 = 0let index2 = 0while(index1 < len1 && index2 < len2) {const num1 = nums1[index1]const num2 = nums2[index2]if (num1 === num2) {res.push(num1)index1++index2++} else if (num1 < num2) {index1++} else {index2++}}return res}
