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 编程工作提供实用帮助。
作者最新文章
JS split切割后出现空字符串怎么过滤
2026-11-05 16:00:30
在 React 或 Vue 项目中封装使用 JS 节流防抖
2026-11-05 15:27:29
JavaScript中怎么将带小数的字符串转为整数?
2026-11-05 14:32:38
怎么用JavaScript策略模式重构电商促销计算逻辑?
2026-11-05 14:01:09
JS使用constructor判断数据类型可靠吗
2026-11-05 13:49:41
