최대 1 분 소요

part49. 순위 검색

js ver 1.0

function solution(info, query) {
    const infoMap = info.reduce((acc, item) => {
        const arr = item.split(' ');
        const score = +arr.pop();

        const id = arr.join('');
        acc[id] = !acc[id] ? [score] : [score, ...acc[id]];
        return acc;
    }, {});
    
    for(const id in infoMap){
        infoMap[id] = infoMap[id].sort((a, b) => a - b);
    }

    return query.map(q => {
        const where = q.split(' ').filter(el => !['and', '-'].includes(el));
        const score = where.pop();

        return Object.keys(infoMap)
            .filter(key => where.every(condition => key.includes(condition)))
            .reduce((cnt, key) => {
                const scoreArr = infoMap[key];
                cnt += scoreArr.slice(binarySearch(scoreArr, score)).length;
                return cnt;
            }, 0);
    });
}

const binarySearch = (arr, target) => {
    let left = 0;
    let right = arr.length;

    while (left < right) {
        const mid = Math.floor((left + right) / 2);

        if (arr[mid] >= target) {
            right = mid;
        } else {
            left = mid + 1
        }
    }

    return left;
}

실행결과_js ver 1.0


업데이트: