JavaScript 获取两个数组交集的方法

作者:函数茶馆时间:2026-10-29 10:49:05浏览:69

本文介绍了一种在 JavaScript 中获取两个已排序数组交集的高效方法。该算法利用双指针技术,通过比较元素大小来移动指针,时间复杂度为 O(n),其中 n 为两数组长度较小值。代码展示了具体实现及调用示例,适合需要处理有序数据集合的场景。

获取排序数组交集的方法

本文介绍了一种在 JavaScript 中获取两个数组交集的实现方式,供开发者参考。

使用该函数时,传入的两个数组必须已经是排序状态。


/* finds the intersection of 
 * two arrays in a simple fashion. 
 *
 * PARAMS
 * a - first array, must already be sorted
 * b - second array, must already be sorted
 *
 * NOTES
 *
 * Should have O(n) operations, where n is 
 *  n = MIN(a.length(), b.length())
 */
function arrayIntersection(a, b)
{
 var ai=0, bi=0;
 var result = new Array();
 while( ai < a.length && bi < b.length )
 {
   if (a[ai] < b[bi] ){ ai++; }
   else if (a[ai] > b[bi] ){ bi++; }
   else /* they're equal */
   {
    result.push(a[ai]);
    ai++;
    bi++;
   }
 }
 return result;
}
console.log(arrayIntersection([1,2,3],[2,3,4,5,6]));//[2,3]

希望这段代码能对您的 JavaScript 编程工作提供实用帮助。

作者最新文章