给定两个数组,编写一个函数来计算它们的交集。

    1. /**
    2. * 哈希表
    3. * 时间复杂度:O(m+n)
    4. * 空间复杂度:O(min(m,n))
    5. */
    6. var intersect1 = function (nums1, nums2) {
    7. const map = {}
    8. const res = []
    9. for (const n of nums1) {
    10. map[n] = (map[n] || 0) + 1
    11. }
    12. for (const n of nums2) {
    13. if (map[n]) {
    14. map[n]--
    15. res.push(n)
    16. }
    17. }
    18. return res
    19. }
    1. /**
    2. * 排序、快慢指针
    3. * 时间复杂度:O(mlogm+nlogn)
    4. * 空间复杂度:O(logm+logn)
    5. */
    6. var intersect = function (nums1, nums2) {
    7. nums1.sort((x, y) => x - y)
    8. nums2.sort((x, y) => x - y)
    9. const len1 = nums1.length
    10. const len2 = nums2.length
    11. const res = []
    12. let index1 = 0
    13. let index2 = 0
    14. while(index1 < len1 && index2 < len2) {
    15. const num1 = nums1[index1]
    16. const num2 = nums2[index2]
    17. if (num1 === num2) {
    18. res.push(num1)
    19. index1++
    20. index2++
    21. } else if (num1 < num2) {
    22. index1++
    23. } else {
    24. index2++
    25. }
    26. }
    27. return res
    28. }