-
Notifications
You must be signed in to change notification settings - Fork 890
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
找出两个数组的交集元素 #806
Comments
|
function intersection (arr, arr1) { |
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)); |
直接使用 {} 作为 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])); |
# for free
to join this conversation on GitHub.
Already have an account?
# to comment
No description provided.
The text was updated successfully, but these errors were encountered: