✅ 폰캣몬의 종류를 key 로 가지는 해시맵 사용하여 종류 수 구하기 ➡︎ 같은 키 중복 시, 덮어쓰기
HashMap<Integer,Integer> map = new HashMap<>();
✅ N마리의 폰켓몬 중 N/2 마리를 가져가도 된다 ➡︎ 가져갈 수 있는 최대의 종류 가짓수는 N/2
최대 가져갈 수 있는 폰켓몬 수 : nums.length/2
폰켓몬 종류의 수 : map.size()
✅ 폰캣몬 종류 수 <= 최대 가져갈 수 있는 폰켓몬 수 라면,
가져갈 수 있는 폰켓몬 수가 많아도, 가져갈 수 있는 종류 수는 전체 종류 수와 같다.
- 나의 코드
import java.util.HashMap;
class Solution {
public int solution(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
int answer = nums.length/2;
int size = 0;
for(int n : nums) {
map.put(n,0);
}
size = map.size();
if(size <= answer) {
answer = size;
}
return answer;
}
}
+
✅ nums 리스트에서 중복을 제거한 집합(set)을 구함
HashSet<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toCollection(HashSet::new))
(int)Arrays.stream(nums).distinct().count()
- 다른 풀이 방식
import java.util.Arrays;
import java.uitl.HashSet;
import java.util.stream.Collectors;
class Solution {
public int solution(int[] nums) {
HashSet<Integer> set = Arrays.stream(nums).boxed().collect(Colletors.toCollection(HashSet::new));
int n = nums.length;
int k = n /2;
return Math.min(k, set.size());
// 또는
// return Math.min((int)Arrays.stream(nums).distinct().count(), nums.length/2);
}
}