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

배열에 k 번째까지 높은 빈도수를 갖는 숫자를 찾아서 배열로 반환하는 문제이다.
Map, PriorityQueue, 자료구조를 이용하여 해결하였다. 빈도수를 체크하기 위해 Map의 key,value 를 이용하였고, 높은 빈도수를 갖는 숫자로 정렬하기 위해서 PriorityQueue와 Comparable을 구현한 클래스를 만들어 주었다. 통과 코드는 아래와 같다.

import java.util.*;  
  
public class Solution {  
    public int[] topKFrequent(int[] nums, int k) {  
        Map<Integer, Element> map = new HashMap<>();  
  
        for(int num: nums){  
            map.compute(num, (key, element) -> {  
                if(element == null){  
                    element = new Element(num);  
                }else{  
                    element.freq++;  
                }  
                return element;  
            });  
        }  
  
        PriorityQueue<Element> pq = new PriorityQueue<>();  
        for(Element e : map.values()){  
            pq.add(e);  
        }  
  
        int[] answer = new int[k];  
        for(int i = 0; i < k; i++){  
            answer[i] = pq.poll().value;  
        }  
  
        return answer;  
    }  
  
    private static class Element implements Comparable<Element>{  
        int value;  
        int freq;  
  
        Element(int value){  
            this.value = value;  
            this.freq = 1;  
        }  
  
        @Override  
        public int compareTo(Element o){  
            return o.freq - this.freq;  
        }  
    }  
}

'Algolithm-Leetcode > Arrays & Hashing' 카테고리의 다른 글

Group Anagrams  (0) 2026.08.20
Contains Duplicate  (0) 2026.08.14
Valid Anagram  (0) 2026.08.07
Two Sum  (0) 2026.07.21

+ Recent posts