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

https://leetcode.com/problems/contains-duplicate/description/

 

Contains Duplicate - LeetCode

Can you solve this real interview question? Contains Duplicate - Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.   Example 1: Input: nums = [1,2,3,1] Output: true Ex

leetcode.com

 

주어진 배열에 중복된 값이 있는지 체크하는 문제이다.
중복과 관련해서 가장 쉽게 사용할 수 있는 자료구조는 Set 이다.
Set은 중복된 값을 넣을 경우 제거되고 하나의 값으로 저장되기 때문이다.
배열의 값을 순차적으로 넣으며 Set의 크기가 변하는지 확인하여 해결해주었다.

import java.util.*;  
  
public class Solution {  
    public boolean containsDuplicate(int[] nums) {  
        Set<Integer> set = new HashSet<>();  
        int size = 0;  
        for(int i = 0; i < nums.length; i++){  
            size++;  
            set.add(nums[i]);  
            if(size != set.size()) return true;  
        }  
  
        return false;  
    }  
}

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

Top K Frequent Elements  (0) 2026.08.23
Group Anagrams  (0) 2026.08.20
Valid Anagram  (0) 2026.08.07
Two Sum  (0) 2026.07.21

 

두 문자열이 주어지고 하나의 문자열을 이루는 문자의 순서를 바꾸어 재구성 할 수 있는지 묻는 문제였다. 재구성 할 수 있다는 것은 동일한 개수의 문자를 가지고 있는 것이다.

따라서 알파벳 각각이 몇 개 있는지 확인하였다.
확인하기 위해서 알파벳 개수 크기의 배열을 두 개 만든 후 각각의 문자에 따라 배열의 인덱스의 값을 올려주었다. 그리고 두 배열의 값들을 비교하면 결과를 확인할 수 있다.

public class Solution {  
    public boolean isAnagram(String s, String t) {  
        // 글자의 길이가 다르다면 다른 것, for 문의 s.length()로 두 문자열의 문자를 순회할 것이므로 체크  
        if(s.length() != t.length()) return false;  
  
        int[] word1 = new int[26];  
        int[] word2 = new int[26];  
        for(int i  = 0; i < s.length(); i++){  
            // 문자에 따라 인덱스의 값 증가, 'a'의 값 0번 인덱스로 하여 기준으로 한다.  
            word1[s.charAt(i) - 'a']++;  
            word2[t.charAt(i) - 'a']++;  
        }  
  
        for(int i = 0; i < word1.length; i++){  
            // 문자의 조합이 똑같은지 확인  
            if(word1[i] != word2[i]) return false;  
        }  
  
        return true;  
    }  
}

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

Top K Frequent Elements  (0) 2026.08.23
Group Anagrams  (0) 2026.08.20
Contains Duplicate  (0) 2026.08.14
Two Sum  (0) 2026.07.21

https://leetcode.com/problems/two-sum/description/

 

Two Sum - LeetCode

Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not

leetcode.com

 

 

두 값의 합이 Target과 일치하는 인덱스를 배열로 반환하는 문제이다.
알고리즘이 필요하기보다. 배열을 다룰 수 있는 지에 가까운 문제였다.

class Solution {
public int[] twoSum(int[] nums, int target){  
    for(int i = 0; i < nums.length; i++){  
        for(int j = i + 1; j < nums.length; j++){  
            if(nums[i] + nums[j] == target){  
                return new int[]{i, j};  
            }  
        }  
    }  
	return null;  
}

 

 

문제에서 반드시 하나의 답이 존재한다고 조건을 주어서 순회가 끝난 경우 null 로 처리하였다.
Exception으로 처리하려 하였으나 리트코드에서는 문제에서 별도의 익셉션 처리를 할 수 없는 듯 하였다. throws Exception 메세지를 추가하자 아래와 같은 오류가 발생하였다.

Line 7: error: unreported exception Exception; must be caught or declared to be thrown [in __Driver__.java] int[] ret = new Solution().twoSum(param_1, param_2); ^

 

로드맵의 첫 문제라서 그런지 굉장히 쉬웠다.

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

Top K Frequent Elements  (0) 2026.08.23
Group Anagrams  (0) 2026.08.20
Contains Duplicate  (0) 2026.08.14
Valid Anagram  (0) 2026.08.07

+ Recent posts