프로그래머스 알고리즘 고득점 Kit 카테고리의 해시 문제 중 레벨 1 폰켓몬 문제를 풀이했다.
문제 조건 중 최대 nums / 2 만큼의 폰켓몬을 가져갈 수 있다고 하여, 최대 개수를 구하고 실제 가져갈 수 있는 폰켓몬은 그보다 작을 수 있기 때문에 set을 통해 중복을 제거하여 해당 set의 길이를 구하고 두 길이 중 더 작은 값을 리턴하도록 풀이했다.
PonKeMon.java
package com.example.Programmers.Lv1;
import java.util.Arrays;
import java.util.HashSet;
import java.util.stream.Collectors;
/**
* 프로그래머스 Lv1 - 폰켓몬
*/
public class PonKeMon {
public int solution(int[] nums) {
int maxCnt = nums.length / 2;
HashSet<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toCollection(HashSet::new));
int minCnt = set.size();
return Math.min(minCnt, maxCnt);
}
}
PonKeMonTest.java
package com.example.Programmers.Lv1;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class PonKeMonTest {
@Test
public void nearSameWordTest() {
PonKeMon p = new PonKeMon();
int result1 = p.solution(new int[] { 3, 1, 2, 3 });
int result2 = p.solution(new int[] { 3, 3, 3, 2, 2, 4 });
int result3 = p.solution(new int[] { 3, 3, 3, 2, 2, 2 });
assertEquals(2, result1);
assertEquals(3, result2);
assertEquals(2, result3);
}
}