給定兩個陣列 list1、list2,取出兩者都存在的元素(交集)。
function intersectionDoubleLoop(list1, list2) {
const result = [];
for (let i = 0; i < list1.length; i++) {
for (let j = 0; j < list2.length; j++) {
if (list1[i] === list2[j]) {
result.push(list1[i]);
break; // 避免重複加入
}
}
}
return result;
}
⚠️ 若陣列含重複值,結果會重複;需額外去重。
function intersectionSet(list1, list2) {
const set2 = new Set(list2); // O(m) 建立查找表
return [...new Set(list1.filter(x => set2.has(x)))]; // 去重 + 過濾
}
Set.has() 平均 O(1),整體線性複雜度。new Set(...) 自動去重,結果無重複值。function intersectionSorted(arr1, arr2) {
const a = [...arr1].sort((x,y)=>x-y);
const b = [...arr2].sort((x,y)=>x-y);
const res = [];
let i=0, j=0;
while (i
| 方法 | 耗時 | 記憶體 |
|---|---|---|
| 雙重迴圈 | ~12 秒 | 低 |
| Set + filter | ~15 ms | 中 |
| 排序雙指標 | ~40 ms | 中 |