


나의 풀이
import java.util.*;
class Solution {
public int solution(int[] nums) {
int answer = 0;
ArrayList<Integer> list = new ArrayList<>(); // 1
for (int i = 0; i < nums.length; i++) {
if (!(list.contains(nums[i])) && list.size() < (nums.length / 2)) list.add(nums[i]); // 2
}
return answer = list.size(); // 3
}
}
과정
- 폰켓몬을 담을 list 선언
- 만약 list에 nums[i]가 없고, list의 크기가 nums 크기의 1/2보다 작다면 list에 nums[i]를 추가
- list의 크기를 반환
다른 사람 풀이
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)));
}
}
- Collectors.toSet()로 모든 요소를 중복없이 Set에 수집 -> 폰켓몬의 종류
- Collectors.collectingAndThen()로 Set의 크기와 nums 배열 길이의 절반 중 작은 값을 반환 -> nums 배열 길이의 절반이 더 작다면 어차피 절반의 길이가 최대 종류의 수