เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลขที่มีค่าซ้ำซ้อน และส่งกลับตัวเลขที่ปรากฏมากกว่า (n/2) จำนวนครั้งที่ n คือความยาวของอาร์เรย์ หากไม่มีองค์ประกอบดังกล่าวในอาร์เรย์ ฟังก์ชันของเราจะคืนค่าเท็จ
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
const arr = [12, 5, 67, 12, 4, 12, 4, 12, 6, 12, 12];
const arr1 = [3, 565, 7, 23, 87, 23, 3, 65, 1, 3, 6, 7];
const findMajority = arr => {
let maxChar = -Infinity, maxCount = 1;
// this loop determines the possible candidates for majorityElement
for(let i = 0; i < arr.length; i++){
if(maxChar !== arr[i]){
if(maxCount === 1){
maxChar = arr[i];
} 0else {
maxCount--;
};
} else {
maxCount++;
};
};
// this loop actually checks for the candidate to be the majority
element
const count = arr.reduce((acc, val) => maxChar===val ? ++acc : acc, 0);
return count > arr.length / 2;
};
console.log(findMajority(arr));
console.log(findMajority(arr1)); ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น -
true false