PS/LeetCode

LeetCode / Heap / 692번 / Top K Frequent Words / JS

KimMinJun 2023. 4. 18. 01:44

< 문제 바로가기 >

 

Top K Frequent Words - LeetCode

Can you solve this real interview question? Top K Frequent Words - Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequenc

leetcode.com

 

< 문제 간단설명 >

단어들이 들어있는 배열 words 배열과 정수인 k가 들어온다. words 배열에서 가장 많이 나온 단어들을 순서대로 k개만 반환한다. 이 때, 사전식으로 정렬하여 반환한다.

 

/**
 * @param {string[]} words
 * @param {number} k
 * @return {string[]}
 */
var topKFrequent = function(words, k) {
    const customSort = (a, b) => {
        let [stringA, countA] = a;
        let [stringB, countB] = b;

        if(countA === countB) {
            // 사전식으로 했을 때 stringA가 stringB 앞에 올 경우 음수를 반환하고,
            // 같다면 0,
            // 뒤에 올 경우엔 양수를 반환한다.
            return stringA.localeCompare(stringB);
        }
        else {
            // 양수면 자리를 바꾸고, 아니면 바꾸지 않는다.
            return countB - countA;
        }
    };

    let wordCountMap = new Map();

    words.forEach((word) => {
        wordCountMap.set(word, wordCountMap.get(word) + 1 || 1);
    });

    let arr = Array.from(wordCountMap).sort((a, b) => customSort(a, b));
    arr = arr.map((el) => el[0]).splice(0, k);
    
    return arr;
};