หา intersection ของสองอาร์เรย์สตริง: สมาชิกที่ปรากฏในทั้งสอง ความถี่ตามจำนวนน้อยที่สุดในแต่ละอาร์เรย์
ตัวอย่าง
arr1 = ['hello', 'world', 'how', 'are', 'you'] arr2 = ['hey', 'world', 'can', 'you', 'rotate'] Output: ['world', 'you']
ตัวอย่างโค้ด
const arr1 = ['hello', 'world', 'how', 'are', 'you'];
const arr2 = ['hey', 'world', 'can', 'you', 'rotate'];
const intersectElements = (arr1, arr2) => {
const res = [];
const smaller = arr1.length < arr2.length ? arr1.slice() : arr2.slice();
const bigger = arr1.length >= arr2.length ? arr1.slice() : arr2.slice();
for (let i = 0; i < smaller.length; i++) {
const idx = bigger.indexOf(smaller[i]);
if (idx !== -1) {
res.push(smaller[i]);
bigger.splice(idx, 1, undefined); // ลบออกเพื่อไม่ให้นับซ้ำ
}
}
return res;
};
console.log(intersectElements(arr1, arr2));
การทำงาน
- วนอาร์เรย์ที่สั้นกว่า (ประหยัดเวลา)
- หาในอาร์เรย์ที่ยาวกว่า ด้วย
indexOf - เจอ → push ผลลัพธ์ และลบออกจาก bigger (
splice)
ผลลัพธ์
[ 'world', 'you' ]
Complexity: O(m×n) สำหรับข้อมูลใหญ่ควรใช้ Map/Set เพื่อ O(m+n)