
😎풀이
words의 각 단어 빈도 수 조회
- 빈도수 기준 오름차 순 정렬
- 동일 빈도인 경우, 사전 기준 오름차 순 정렬
- 정렬된 요소 중
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)
};