Phần tử majority xuất hiện > n/2 lần. Với mảng đã sắp xếp, phần tử majority (nếu có) luôn ở giữa. Kiểm tra phần tử giữa có bằng giá trị cho trước không.
Ví dụ: arr=[5,5,5,12,15], num=5 → true (5 xuất hiện 3/5 > 2.5).
Ví dụ
const arr = [5, 5, 5, 12, 15];
const num = 5;
const isMajority = (arr = [], num = 1) => {
const { length } = arr;
if (!length) return false;
const middle = Math.floor(length / 2);
return arr[middle] === num;
};
console.log(isMajority(arr, num));
Kết quả
true