692. Top K Frequent Words

양성준·2025년 5월 12일

코딩테스트

목록 보기
50/102

문제

https://leetcode.com/problems/top-k-frequent-words/description/

풀이

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>();
        for(String s : words) {
            map.put(s, map.getOrDefault(s,0) + 1);
        }

        PriorityQueue<String> heap = new PriorityQueue<>((a,b) -> {
            if(map.get(a) == map.get(b)) {
                return a.compareTo(b);
            }
            return map.get(b) - map.get(a);
            });

        for(String key : map.keySet()) {
            heap.add(key);
        }

        List<String> list = new ArrayList<>();

        for(int i = 0; i < k; i++) {
            list.add(heap.poll());
        }

        return list;
    }
}
  • String 사전순 비교는 a.compareTo(b);
profile
백엔드 개발자

0개의 댓글