简体   繁体   English

如何获取数组之间的差异并返回它们

[英]How to get the differences between arrays and return them

Im practicing my interviewing skills and i got this problem to solve:我正在练习我的面试技巧,我要解决这个问题:

"Write a function that processes two arrays of integers. Each array will have only distinct numbers (no repeats of the same integer in the same array), and the arrays are not sorted. find out which numbers are in array 1, but not array 2, and which numbers are in array 2, but not in array 1" "编写一个函数处理两个整数数组。每个数组将只有不同的数字(同一数组中相同的整数没有重复),并且数组没有排序。找出哪些数字在数组1中,而不在数组中2,哪些数字在数组 2 中,但不在数组 1 中”

im trying to polish my ES6+ skills too so i know that a good way to loop through them is using array.map and also if i want the difference i need Array.prototype.filter() This way, i will get an array containing all the elements of arr1 that are not in arr2 and vice-versa我也在努力提高我的 ES6+ 技能,所以我知道循环它们的一个好方法是使用 array.map,如果我想要差异,我需要 Array.prototype.filter() 这样,我会得到一个包含所有的数组arr1 中不在 arr2 中的元素,反之亦然

symmetric or non symmetric you ask?你问对称还是非对称?

i'll go with the fastest please我会以最快的速度去

thanks!谢谢!

Below two implementations.下面两个实现。

The first one favors readability and is suitable for normal-sized arrays.第一个有利于可读性,适用于正常大小的数组。

You can't go asymptotically faster than the second method (complexity in O(n*log(n)) ), although you can go faster for smaller arrays and reduce linearly the number of instructions executed.您不能比第二种方法渐近地更快(复杂度为O(n*log(n)) ),尽管您可以更快地处理较小的数组并线性减少执行的指令数量。

 const arr1 = [1,2,9,8,6,7]; const arr2 = [8,6,3,4,1,0]; // most readable console.log( // arr1 without arr2 arr1.filter(x => arr2.indexOf(x)==-1), // arr1 and arr2 arr1.filter(x => arr2.indexOf(x)!=-1), // arr2 without arr1 arr2.filter(x => arr1.indexOf(x)==-1) ); // fastest - O(nln(n)) (() => { const count = // concatenate - O(n) [...arr1, ...arr1, ...arr2] // sort - O(nln(n)) .sort() // count - O(n) .reduce((acc, cur) => { acc[cur] = (acc[cur] || 0) +1; return acc; }, {}); // separate - O(n) const a1 = []; const a12 = []; const a2 = []; for (let i in count) { switch(count[i]) { case 1: a2.push(+i); break; case 2: a1.push(+i); break; case 3: a12.push(+i); break; } } console.log( a1, // arr1 without arr2 a12, // arr1 and arr2 a2 // arr2 without arr1 ); })();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM