크기가 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