JavaScript 中不同字符串之间的相似性

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/1 13:32:17

我们有两个数字数组,我们需要编写一个函数 Intersection() 来计算它们的交集并返回一个包含相交元素的数组,该数组的顺序任意。结果中的每个元素应与它在两个数组中显示的次数相同。

例如:

如果输入为 −

arr1 = ['hello', 'world', 'how', 'are', 'you'];
arr2 = ['hey', 'world', 'can', 'you', 'rotate'];

那么输出应该是 −

['world', 'you'];

方法:

如果数组已经排序,我们可以使用双指针方法,最初两个指针都指向 0,即各自数组的开头,然后我们可以继续增加相应的指针,这将是 O(m+n) 复杂度,其中 m 和 n 是数组的大小。

但由于我们的数组未排序,因此对数组进行排序然后使用这种方法没有任何逻辑,我们将检查第一个值与第二个值的每个值,并构造一个交集数组。

这将花费我们 O(n^2) 的时间。

因此,让我们编写该函数的代码 −

示例

其代码为 −

arr1 = ['hello', 'world', 'how', 'are', 'you'];
arr2 = ['hey', 'world', 'can', 'you', 'rotate'];
const intersectElements = (arr1, arr2) => {
   const res = [];
   const { length: len1 } = arr1;
   const { length: len2 } = arr2;
   const smaller = (len1 < len2 ? arr1 : arr2).slice();
   const bigger = (len1 >= len2 ? arr1 : arr2).slice();
   for(let i = 0; i < smaller.length; i++) {
      if(bigger.indexOf(smaller[i]) !== -1){
         res.push(smaller[i]);
         bigger.splice(bigger.indexOf(smaller[i]), 1, undefined);
      }

   };
   return res;
};
console.log(intersectElements(arr1, arr2));

输出

控制台中的输出将是 −

[ 'world', 'you' ]

相关文章


有用资源