day147-LeetCode 349. Intersection of Two Arrays

题目

Given two arrays, write a function to compute their intersection.

Example:

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

Each element in the result must be unique.

The result can be in any order.

分析

选较短的数组去和长数组比较;
短数组值依次遍历长数组;
找短数组中有相应的值;

题解

function intersection (arr1, arr2) {
let result = []
let longArr
let shortArr
if (arr1.length > arr2.length) {
longArr = arr1
shortArr = arr2
} else {
shortArr = arr1
longArr = arr2
}
for (let i = 0; i < shortArr.length; i++) {
let value = shortArr[i]
// 如果longArr中有shortArr的值,而且在交集数组中没有,则为新交集
if(longArr.indexOf(value) >= 0 && result.indexOf(value) === -1) {
result.push(value)
}
}
return result
}

// 其实es6可以用很快的方法解决
let intersection = arr1.filter(x => new Set(arr2).has(x))
文章作者: lmislm
文章链接: http://lmislm.com/2019/06/09/2019-06-09/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog