코딩테스트

[프로그래머스/Java] 폰켓몬 (HashSet)

데메즈 2026. 7. 5. 22:08
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/1845

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

1. HashMap 이용 : 카운팅이 필요할 때

import java.util.HashMap;
import java.lang.Math;

class Solution {
    public int solution(int[] nums) {
        int answer = 0;
        
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int item : nums)
            map.put(item, map.getOrDefault(item, 0)+1);
        
        answer = Math.min(map.size(), nums.length/2);
        
        return answer;
    }
}

 

 

2. HashSet 이용 : 존재 여부 / 중복 제거만 필요할 때

import java.util.HashSet;

class Solution {
    public int solution(int[] nums) {
        
        // 1. 중복을 제거할 HashSet 주머니를 만든다
        HashSet<Integer> set = new HashSet<>();
        
        // 2. 배열을 HashSet에 집어넣는다
        for(int num : nums){
            set.add(num);
        }
        
        // 3. 주머니에 남은 "폰켓몬 종류의 개수"
        int types = set.size();
        
        return Math.min(types, nums.length/2);
    }
}
반응형