1. Intersection of two numbers
349. Intersection of Two Arrays
Difficulty Easy 716
Given two arrays
nums1
and sumnums2
, return their intersection . Each element in the output must be unique . We can ignore the order of the output results .Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanation: [4,9] is also passablehint:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
Method 1: Complete through set and filter
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersection = function(nums1, nums2) {
return Array.from(new Set(nums1.filter(num1=>nums2.includes(num1))))
};
Method 2: After sorting, it is done by double pointer
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersection = function(nums1, nums2) {
nums1.sort((a,b)=>a-b)
nums2.sort((a,b)=>a-b)
const common = []
let num1Index = 0, num2Index = 0
// 这里是 && 而不是 ||; 只要有一个遍历完就结束
while(num1Index < nums1.length && num2Index < nums2.length) {
const num1 = nums1[num1Index]
const num2 = nums2[num2Index]
if(num1 === num2) {
num1Index++
num2Index++
!common.includes(num1) && common.push(num1)
}
if(num1 > num2) {
num2Index++
}
if(num1 < num2) {
num1Index++
}
}
return common
};
2. Multi-array intersection
Analysis: Multi-array is to continue to compare the results of the first two merged arrays. It can be realized by reduce.
function getIntersect(...arrs) {
return arrs.reduce(function(prev,cur){
return [...new Set(cur.filter((item)=>prev.includes(item)))]
})
}