본문 바로가기
자바스크립트

[javascript] 최빈값 구하기

by 슈크림 붕어빵 2023. 7. 6.

1. O(n^2)

function solution(array) {
    var min = 0;
    var minCount =0;
    for (var i=0;i<array.length;i++){
        var count = 0;
        for(var j = 0;j<array.length;j++){
            if (array[i]==array[j]){
                count++;   
            }   
        }
        if(count > minCount )
            {
                minCount = count;
                min = array[i];
                
            }
        else if(count == minCount && min!=array[i]){
            min = -1
        }
    }
    return min;
}

2. 해시맵 이용 O(n)

function solution(array) {
    let map = new Map();
    let max = [-1, -1];

    for (let i = 0; i<array.length; i++) {
        let tmp = array[i];
        let count = map.has(tmp) ? map.get(tmp) + 1 : 1;
        
        map.set(tmp, count);

        if (count > max[0]) {
            max[0] = count;
            max[1] = tmp;
        } 
        else if (count == max[0]) {
            max[1] = -1;
        }
    }

    return max[1];
}