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

https://leetcode.com/problems/group-anagrams/

 

Group Anagrams - LeetCode

Can you solve this real interview question? Group Anagrams - Given an array of strings strs, group the anagrams together. You can return the answer in any order.   Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan

leetcode.com

 

동일한 문자로 구성된 문자열을 묶어주는 문제이다. 문자를 분해한 이후 정렬해주면 그 구성을 확인할 수 있다. 이 확인한 결과를 Map 구조의 키로 이용해주어 각 단어들의 리스트를 만들어 줄 수 있다. 아래의 코드와 같이 해결해 줄 수 있다.

import java.util.*;  
  
public class Solution {  
    public List<List<String>> groupAnagrams(String[] strs) {  
        Map<String, List<String>> map = new HashMap<>();  
        for(String str: strs){  
            char[] c = str.toCharArray();  
            Arrays.sort(c);  
            String reArrange = new String(c);  
            if(!map.containsKey(reArrange)){  
                map.put(reArrange, new ArrayList<>());  
            }  
  
            map.get(reArrange).add(str);  
        }  
  
        return new ArrayList<>(map.values());  
    }  
}

 

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

Top K Frequent Elements  (0) 2026.08.23
Contains Duplicate  (0) 2026.08.14
Valid Anagram  (0) 2026.08.07
Two Sum  (0) 2026.07.21

+ Recent posts