본문 바로가기
Algorithm/문제풀이

[Codility] Dominator (Easy) by javascript - AVAILABLE LESSONS 8

by 썸머워즈 2022. 4. 20.
반응형

▷ 문제 : AVAILABLE LESSONS 8 - Dominator (Easy)

 

Dominator coding task - Learn to Code - Codility

Find an index of an array such that its value occurs at more than half of indices in the array.

app.codility.com

▷ 해결 날짜 : 2022.04.20
▷ 소요 시간 : 15분
▷ 풀이 과정 :

중복되는 숫자의 개수가 배열 길이의 절반보다 큰 경우를 해당 숫자의 인덱스 번호를 출력하는 문제다.

 

map을 사용해 개수를 세주고 그다음에 조건에 맞는 인덱스를 바로 출력해주는 로직을 짜서 풀었다.

 

▷ 구현

function solution(A) {
    if(!A.length) return -1;

    const map = new Map();
    A.forEach(key => {
        map.set(key, map.has(key) ? map.get(key) + 1 : 1);
    });

    const limit = A.length / 2;
    const max = Math.max(...map.values());
    for(let i = 0 ; i < A.length ; i++){
        if(map.get(A[i]) == max){
            return (map.get(A[i]) > limit) ? i : -1
        }
    }
}


▷ 복기 :

더 깔끔하게 풀 수 없었을까 하는 생각이 든다.

반응형


댓글

TOP