เราได้รับอาร์เรย์ขนาด n และเราจำเป็นต้องค้นหาองค์ประกอบส่วนใหญ่ องค์ประกอบส่วนใหญ่คือองค์ประกอบที่ปรากฏมากกว่า [ n/2 ] ครั้ง
ตัวอย่าง
const arr = [2, 4, 2, 2, 2, 4, 6, 2, 5, 2];
const majorityElement = (arr = []) => {
const threshold = Math.floor(arr.length / 2);
const map = {};
for (let i = 0; i < arr.length; i++) {
const value = arr[i];
map[value] = map[value] + 1 || 1;
if (map[value] > threshold)
return value
};
return false;
};
console.log(majorityElement(arr)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
2