import java.util.*;
class Solution {
public int solution(int[] nums) {
int answer = 0;
/*
n -> n/2 선택
종류에 따라 번호
최대한 다양한 폰켓몬(숫자)
가장 많은 번호의 개수 return
*/
int pick = nums.length / 2; //nums가 항상 짝수
//set을 이용하면 중복을 제거할 수 있다.
Set<Integer> numsSet = new HashSet<>();
//중복 제거된 세트
for(int num : nums){
numsSet.add(num);
}
for(int setNum : numsSet){
if(pick > answer){
answer++;
}
}
return answer;
}
}
분석
단순 set을 쓸 수 있는지 묻는 문제
마지막에 굳이 for를 쓰지 않고 분기 처리하여 적은 수를 return 하면 더 빠름
import java.util.*;
class Solution {
public int solution(int[] nums) {
/*
n -> n/2 선택
종류에 따라 번호
최대한 다양한 폰켓몬(숫자)
가장 많은 번호의 개수 return
*/
int pick = nums.length / 2; //nums가 항상 짝수
//set을 이용하면 중복을 제거할 수 있다.
Set<Integer> numsSet = new HashSet<>();
//중복 제거된 세트
for(int num : nums){
numsSet.add(num);
}
if(pick > numsSet.size()){
return numsSet.size();
}
return pick;
}
}