개발 공부/코딩테스트

99클럽 코테 스터디 10일차 TIL - 해시

죽밥죽밥화이팅 2024. 11. 6. 23:51

문제

프로그래머스 [포켓몬]

문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/1845

 

해결 방법

  • HashSet을 사용하여 nums 배열에 있는 모든 폰켓몬 번호를 중복 없이 저장한다.
  • maxSelect 변수에 N/2 값을 저장한다. -> 선택 가능한 폰켓몬 수의 최대치이다.
  • Math.min(set.size(), maxSelect)를 사용하여 선택 가능한 폰켓몬 종류의 최대 개수를 계산한다.
  • 종류 수가 선택 가능한 수를 초과하는 경우,  작은 값을 반환한다.


코드

import java.util.HashSet;

class Solution {
    public int solution(int[] nums) {
        // 1. 중복 없는 폰켓몬 종류의 개수를 구하기 위해 HashSet 사용
        HashSet<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        
        // 2. 최대 선택 가능한 폰켓몬 수 계산
        int maxSelect = nums.length / 2;
        
        // 3. 결과는 폰켓몬 종류 수와 maxSelect 중 작은 값을 반환
        return Math.min(set.size(), maxSelect);
    }
}

 


 

  • 참고할 다른 풀이 방법
더보기
  • 스트림 
import java.util.Arrays;
import java.util.stream.Collectors;

class Solution {
    public int solution(int[] nums) {
        return Arrays.stream(nums)
                .boxed()
                .collect(Collectors.collectingAndThen(Collectors.toSet(),
                        phonekemons -> Integer.min(phonekemons.size(), nums.length / 2)));
    }
}

 

 

import java.util.HashMap;

class Solution {
    public int solution(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();

        for (int i = 0; i < nums.length; i++)
            map.put(nums[i], 1);

        return map.size() > nums.length / 2 ? nums.length / 2 : map.size();
    }
}