-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第 142 题:(算法题)求多个数组之间的交集 #293
Comments
142 |
let a = new Set([1, 2, 3]); |
|
function intersect(...args) {
if (args.length === 0) {
return []
}
if (args.length === 1) {
return args[0]
}
return args.reduce((result, arg) => {
return result.filter(item => arg.includes(item))
})
} |
let getMix = arr => {
return arr.reduce((total, item, index) => {
if (index === 0) {
return [...total, ...item]
}
else {
return total.filter(v => item.includes(v))
}
}, [])
}
getMix([[1],[1,2],[1,3]]) //[1] |
let array1 = [1,2,3,4,5,6]; |
function intersection(...args){
} |
const arr1 = [1, 2, 3];
const arr2 = [3, 4, 5];
const arr3 = [3, 6, 7];
const handle = (...arr) => {
return arr.reduce((rst, ele, i) => {
return rst.filter(item => ele.includes(item));
});
}
handle(arr1, arr2, arr3); |
输入的数组有可能出现重复数据,需要多一步判断;如果输入的是集合,就不用这么复杂了 function intersectN(...arrs) {
if (arrs.length === 1) return arrs[0];
if (arrs.length === 2) return intersect2(...arrs);//如果只有两个 无需reduce 直接求
return arrs.reduce((a, b) => b = intersect2(a, b))
}
function intersect2(nums1, nums2) {
//求两个数组的交叉数组
let res = [];
let obj = toMap(nums1);
for (let i of nums2) {
if (obj[i]) {
res.push(i)
obj[i]--
}
}
return res;
}
function toMap(arr) {
//辅助函数 用于将数组转成map 键值分别是元素和其数量
let obj = {}
for (let i of arr) {
if (obj[i]) obj[i]++
else obj[i] = 1
}
return obj
}
let arr1 = [1, 2, 3, 4, 5, 6, 7, 1, 5]
let arr2 = [3, 5, 4, 1, 5]
let arr3 = [5, 7, 1, 3, 1, 5]
console.log(intersectN(arr1, arr2, arr3)) //[ 5, 1, 3, 5 ] |
function intersection(){
let min_arr=arguments[0],intersect=[];
for (let i=0;i<arguments.length;i++) {
if(min_arr.length > arguments[i].length){ min_arr = arguments[i];}
}
for(let i=0;i<min_arr.length;i++){
let flag = true;
for (let j=0;j<arguments.length;j++) {
if(!arguments[j].includes(min_arr[i])){
flag = false;break;
}
}
if(flag){
if(!intersect.includes(min_arr[i])){
intersect.push(min_arr[i])
}
}
}
return intersect
}
let arr = [1,2,3,4,5,6,7,8,9,10,10],arr1=[5,4,2,9,3,7,21],arr2=[9,3,5,4,11,3];
console.log(intersection(arr,arr1,arr2)) // [9, 3, 5, 4] |
处理数组var a = [1, 2, 3, 5]
var b = [2, 4, 5, 1]
var c = [1, 3, 5]
var intersect
function fn(...arg){
intersect = arg.reduce((total,next)=>{return total.filter(item=>next.includes(item))})
}
fn(a,b,c)
console.log(intersect)
// [1,5] 处理数组和类数组(有iterable接口的数据结构)var intersect
function fn2 (...arg){
intersect = arg.reduce((total,next)=>{return [...total].filter(item=>new Set(next).has(item))})
}
var a = [1, 2, 3, 5]
var b = [2, 4, 5, 1]
var c = [1, 3, 5]
fn2(a,b,c)
console.log(intersect)
// [1,5]
a = new Set([1, 2, 3, 5])
b = new Set([2, 4, 5, 1])
c = new Set([1, 3, 5])
fn2(a,b,c)
console.log(intersect)
//[1,5] |
function getSameItem(arr, ...rest) {
return arr.filter(item => rest.every(restArr => restArr.indexOf(item) > -1))
} |
const p1 = [
|
var arr=[1,2,3] function setArr(...arg){ } |
如果是对象数组上面是不是好多都不管用了 |
|
ClarifySince the description kind of loose, So Let's make it clear. Suppose that, all the list are unique , eg: [1,2,2,3] is not allow.Otherwise the solution could be quiet ugly. Concise Solution -
|
let a = [1, 2, 3]; |
function findJoin(...rest) {
if (rest.length === 0) return [];
return Array.from(rest.reduce((result, arr) => {
return new Set(result.filter(item => arr.includes(item)))
}))
} |
|
function inersection(a,b){
if(!a.length || !b.length){
return [];
}
const map = {};
const result = [];
for(let i=0; i<a.length; i++){
map[a[i]] = map[a[i]] ? ++map[a[i]] : 1;
}
for(let i=0; i<b.length; i++){
if(map[b[i]]){
result.push(b[i]);
map[b[i]]--;
}
}
return result
}
function inersections(){
if(arguments.length<2){
return [];
}
const args = Array.prototype.slice.call(arguments);
const result = [];
let temp = inersection(args[0],args[1]);
let i = 2;
while(i<args.length){
temp=inersection(temp,args[i])
i++;
}
return temp;
}
inersections([1,2,2,1],[2,2],[2,2,4],[2]);//2 |
const a = [1, 2, 2, 3]
const b = [2, 2, 3, 4, 5]
const c = [2, 2, 3, 6, 7, 2]
const intersect = (...args) =>
args.reduce(
(acc, cur) => acc.filter(val => cur.includes(val)),
args[0] || []
)
console.log(intersect(a, b, c)) |
在返回结果那里应该做一个去重 |
|
给定两个数组,编写一个函数来计算它们的交集。
console.log(intersect3([4,9,5],[9,4,9,8,4])); |
function intersect(...arrays) {
let set = new Set(arrays[0])
for(let i=1; i< arrays.length; i++) {
let tmpSet = new Set(arrays[i])
set = new Set([...set].filter(x => tmpSet.has(x)))
}
return [...set]
}
var items = intersect([1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6])
console.log(items) |
|
your code has bug,see example |
认真看我的前提,谢谢 |
function getIntersection (...args) {
//判读是一个还是多个数组
if (args.length > 1) {
return args.reduce((pre, cur)=> {
let preResult = [...new Set(pre)].filter(item => cur.includes(item) );
//用数组的 includes 或者 set 的has方法验证
//let preResult = [...new Set(pre)].filter(item => new Set(cur).has(item) );
return preResult
})
} else {
return args[0]
}
}
console.log(getIntersection([1,2,2,3], [2,2,3,4,5],[3,4,5])
)
|
const a = [1,2,3,1,4,5], b = [3,3,2,5], c = [1,1,1,3,2];
const uniq = arr => [...new Set(arr)];
const mix = (arg1,...arrs) => {
const uniqArr = uniq(arg1);
return arrs.reduce((result, arr) => {
return result.filter(ele => arr.includes(ele));
}, uniqArr);
};
console.log(mix(a,b,c)); // [2,3] |
|
参考@fengshenhai-0727大兄弟的,即使数组有重复的交集项也没问题。 function getTwoArrsCommon(arr1, arr2) {
if(!arr1.length || !arr2.length) {
return [];
}
const res = [];
const map = {};
for(let k of arr1) {
if(map[k]) {
map[k]++;
} else {
map[k] = 1;
}
}
for(let k of arr2) {
if(map[k] > 0) {
res.push(k);
map[k]--;
}
}
return res;
}
function getManyArrsCommon() {
if(arguments.length < 2) {
return [];
}
const args = Array.from(arguments);
let res = getTwoArrsCommon(args[0], args[1]);
let i = 2;
while(i < args.length) {
res = getTwoArrsCommon(res, args[i]);
i++;
}
return res;
}
getManyArrsCommon([1,2,2,1],[2,2],[2,2,4],[2]); // [2]
getManyArrsCommon([1,1,2,3], [1,1,1,2,3,5,5], [1,1]); // [1, 1]
getManyArrsCommon([1,1,3,5,5], [2, 4, 5], [3, 5, 5]); // [5] |
如果第一个数组中有重复的两个1呢,这样算出来,交集中也会有两个1吧 |
中国人为啥要用英文 |
这种算法,[1,1,1,] 和 [] 算出来岂不是 [1,1,1] |
这样算的话,那[1,1,1,2] 和 [1,1,1,] 的交集只有1了 |
function intersection(...arr) {
// 注意 交集是集合概念,集合是不存在重复元素的
const map = {}
const len = arr.length
const result = []
for(let i = 0; i < len; i++) {
const subArr = arr[i]
for (let j = 0 ; j< subArr.length; j++) {
const v = subArr[j]
if(!map[v]) {
map[v] = 1
} else {
map[v] += 1
}
}
}
for(let key in map) {
if(map[key] === len) {
result.push(~~key)
}
}
return result
} |
// 求多个数组之间的交集
function intersection(arr1, arr2) {
let s1 = new Set([...arr1]);
let s2 = new Set([...arr2]);
let result = []
for (let item of s1.values()) {
if (s2.has(item)) {
result.push(item)
}
}
return result;
}
const arr1 = [1,2,3,4,5];
const arr2 = [3,6,7];
const result = intersection(arr1, arr2);
console.log(result);
|
// 不使用set
function intersect<A>(arr1: Array<A>, arr2: Array<A>): Array<A> {
return arr2.filter(x => arr1.indexOf(x) !== -1)
}
// 递归
function intersectAll<A>(arr: Array<Array<A>>): Array<A> {
if (arr.length === 0) return []
else if (arr.length === 1) return arr[0]
else {
const sp = Math.floor(arr.length / 2)
return intersect(intersectAll(arr.slice(0, sp)), intersectAll(arr.slice(sp)))
}
}
// 迭代
function intersectAllReduce<A>(arr: Array<Array<A>>): Array<A> {
if (arr.length === 0) return []
else return arr.slice(1).reduce((pv, cv) => intersect(pv, cv), arr[0])
} |
function intersect(...arrays) {
if (!arrays) {
return [];
}
if (arrays.length === 1) {
return arrays[0];
}
const m = new Map();
for (let i = 0; i < arrays.length; i++) {
for (let j = 0; j < arrays[i].length; j++) {
const key = arrays[i][j];
const value = i + 1;
if (i === 0) {
m.set(key, value);
continue;
}
if (m.has(key) && m.get(key) < value) {
m.set(key, value);
}
}
}
return Array.from(m.keys()).filter((key) => m.get(key) === arrays.length);
} |
console.log(intersect([1,1,1,1,1,2,9,63],[43,1,3,8],[3,3,3,,1,2,4,1,2])) //[1, 1, 1, 1, 1] 这个得到的不算是交集吧 |
你们都好聪明,我只会笨方法 console.log(intersection([1, 1, 1, 1, 1, 2, 9, 63], [43, 1, 3, 8], [3, 3, 3, , 1, 2, 4, 1, 2]))
function intersection() {
var map = new Map()
for (var i = 0; i < arguments.length; i++) {
var arr = [...new Set(arguments[i])]
for (var j = 0; j < arr.length; j++) {
if (!map.has(arr[j])) {
map.set(arr[j], 1)
} else {
map.set(arr[j], map.get(arr[j]) + 1)
}
}
}
var collect = []
for (const iterator of map) {
if (iterator[1] == arguments.length) {
collect.push(iterator[0])
}
}
return collect
} |
`function choose(...arr) { let ret = []; |
/**
* 数组交集
* @param {...Array} arrays
*/
function arrayIntersection(...arrays) {
if (arrays.length === 0) return []
if (arrays.length === 1) return arrays[0]
return arrays.reduce(
(acc, cur) => (acc = acc.filter((accItem) => cur.some((curItem) => curItem === accItem)))
// 或者 (acc, cur) => (acc = acc.filter((accItem) => cur.includes(accItem)))
)
}
/**
* test
*/
const res = arrayIntersection([1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8])
console.log('res: ', res) // [4, 5] |
用分治代码比较简洁, 没考虑性能啥的function intersection(...args) {
if (args.length === 1) return args[0]
if (args.length == 2) return [...new Set(args[0].filter(item => args[1].indexOf(item) !== -1))]
const mid = Math.floor(args.length / 2)
const left = intersection.apply(null, args.slice(0, mid))
const right = intersection.apply(null, args.slice(mid))
return intersection.apply(null, [left, right])
} |
思想来源:借鉴vue diff源码
function intersectionArr(...params) {
let itemCountMap = [];
params.forEach(arr => {
arr.forEach(item => {
itemCountMap[item] = (itemCountMap[item] ? itemCountMap[item] : 0) + 1;
})
})
let itArr = [];
itemCountMap.forEach((item, index) => {
if(item == params.length) {
itArr.push(index);
}
})
return itArr;
}
intersectionArr([1,2,3,4], [2,3], [2,3,4], [1,2,3] ); |
function intersect(...args) {
const flattened = args.reduce((res, arr) => {
return res.concat(arr);
}, []);
return [...new Set(flattened)].filter((v) =>
args.every((arr) => arr.includes(v))
);
} |
function mix(...arrs) {
function createMap(arr) {
return arr.reduce((result, value) => {
result[value] = result[value] || 0
result[value]++
return result
}, {})
}
const mapList = arrs.map(createMap)
const res = mapList.shift()
mapList.reduce((result, map) => {
for (let key in result) {
if (map[key]) {
result[key] = Math.min(map[key], result[key])
} else {
delete result[key]
}
}
return result
}, res)
const result = []
for (let key in res) {
while (res[key]--) {
result.push(key)
}
}
return result
} |
function foo(...args) {
return args.slice(1).reduce(
(acc, cur) => {
return acc.filter((v) => new Set(cur).has(v));
},
[...new Set(args[0])]
);
}
foo([1, 2, 3], [3, 1, 4, 5, 6, 7], [1, 4, 5, 3]); // [1,3] |
https://leetcode.cn/problems/intersection-of-multiple-arrays/submissions/ // 法一: reduce 结合 includes 去重 /**
* @param {number[][]} nums
* @return {number[]}
*/
var intersection = function (nums) {
return nums.reduce((prev, cur) => prev.filter(item => cur.includes(item))).sort((a, b) => a - b);
}; // 法二: map 统计每个元素的个数,如果个数等于 多数组的总数 ,则认为存在交集 /**
* @param {number[][]} nums
* @return {number[]}
*/
var intersection = function (nums) {
const map = new Map;
const res = [];
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums[i].length; j++) {
const item = nums[i][j];
map.set(item, (map.get(item) || 0) + 1);
}
}
for (let [key, value] of map) {
if (value === nums.length) {
res.push(key);
}
}
return res.sort((a, b) => a - b);
}; |
算法
The text was updated successfully, but these errors were encountered: