😎풀이

  1. words의 각 단어 빈도 수 조회
  2. 빈도수 기준 오름차 순 정렬
  3. 동일 빈도인 경우, 사전 기준 오름차 순 정렬
  4. 정렬된 요소 중 k개 반환
function topKFrequent(words: string[], k: number): string[] {
    const freqMap = new Map<string, number>()
    for(const word of words) {
        freqMap.set(word, (freqMap.get(word) ?? 0) + 1)
    }
    const wordSet = new Set<string>(words)
    const sortByFreq = [...wordSet].toSorted((a, b) => {
        const aFreq = freqMap.get(a)
        const bFreq = freqMap.get(b)
        if(aFreq !== bFreq) return bFreq - aFreq
        return a.localeCompare(b)
    })
    return sortByFreq.slice(0, k)
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글