//方法一:用哈希表的思路,将数组转换为对象 var intersect1 = function (nums1, nums2) { let obj = {}, arr = []; for (let i = 0; i < nums1.length; i++){ if (obj[nums1[i]]) obj[nums1[i]] += 1; else obj[nums1[i]] = 1 } for (let j = 0; j < nums2.length; j++){ if (obj[nums2[j]]) { obj[nums2[j]]--; arr.push(nums2[j]) } } return arr } //方法二:先排序后比较 function fn(a, b) { return a - b; } var intersect2 = function(nums1, nums2) { var arr = []; nums1.sort(fn); nums2.sort(fn); var i = 0, j = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] < nums2[j]) { i++; } else if (nums1[i] > nums2[j]) { j++; } else if(nums1[i] == nums2[j]){ arr.push(nums1[i]) i++; j++; } } return arr; }; const nums1 = [1, 2, 2, 1], nums2 = [2, 2]; const newArr = intersect1(nums1, nums2) console.log(newArr) // [2,2]
标签:arr,obj,交集,++,算法,数组,var,nums1,nums2 From: https://www.cnblogs.com/daniller/p/16832845.html