找出两个数组的交集元素
lgwebdream opened this issue · 5 comments
lgwebdream commented
找出两个数组的交集元素
lgwebdream commented
523451928 commented
var a1 = [1, 2, 3, 1]
var a2 = [1, 1]
function intersection(a, b) {
const result = []
const map = a.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1
return acc
}, {})
for (let i = 0; i < b.length; i++) {
if (map[b[i]] >= 0) {
result.push(b[i])
map[b[i]] = map[b[i]] - 1
}
}
return result
}
intersection(a1, a2)
850964517 commented
function intersection (arr, arr1) {
var newArr = arr.concat(arr1)
let res = []
let mapRes = {}
for (var i = 0; i<newArr.length;i++) {
if (mapRes[newArr[i]]) {
mapRes[newArr[i]] += 1
res.push(newArr[i])
} else {
mapRes[newArr[i]] = 1
}
}
return res
}
console.log(intersection(["a","c","d"], ["b","c","d","a"]))
GolderBrother commented
const a = [1, 2, 3, 1]
const b = [1, 1]
function intersection(a, b) {
if (!Array.isArray(a) || !Array.isArray(b)) return null;
const result = [];
const map = a.reduce((accu, cur) => {
accu[cur] = accu[cur] ? accu[cur] + 1 : 1;
return accu;
}, {});
for (let i = 0; i < b.length; i++) {
const item = b[i];
if (map[item]) {
result.push(item);
map[item]--;
}
}
return result;
}
console.log(intersection(a, b));
AAA611 commented
直接使用 {} 作为 map 不能区分数字与字符串类型,使用 Map 代替
const map = new Map()
const res = []
let cur
for (let i = 0; i < arr1.length; i++) {
cur = arr1[i]
if (!map.has(cur)) {
map.set(cur, 1)
} else {
map.set(cur, map.get(cur) + 1)
}
}
for (let j = 0; j < arr2.length; j++) {
cur = arr2[j]
if (map.has(cur)) {
res.push(cur)
let n = map.get(cur)
if (n === 1) {
map.delete(cur)
} else {
map.set(cur, n - 1)
}
}
}
return res
}
console.log(fn([2, 4, 5, 7, 8, 4, 6, 6,'9'], [1, 2, 3, 6, 6, 8, 9, 10]));