Programmers/Java

폰켓몬

Anoi 2023. 1. 29. 19:01

문제

결과

 

풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.*;
 
class Solution {
    public int solution(int[] nums) {
         
        ArrayList<Integer> phone = new ArrayList<>();
       
         for(int i=0; i<nums.length; i++){
              if(!phone.contains(nums[i]))
                  phone.add(nums[i]);            
            }
        
        return phone.size() < nums.length/2 ? phone.size() : nums.length/2;
        
    } 
}
cs

phone이라는 arraylist를 만들고 contains로 중복 검사를 한다.

마지막에 phone의 크기가 nums의 길이의 반보다 작다면 그대로 리턴

아니라면 nums의 길이의 반을 리턴한다.

 

contains를 사용하기 싫다면 아예 중복값을 못 받게 할 수도 있다.

 

Map

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;
 
class Solution {
    public int solution(int[] nums) {
         
       HashMap<Integer, Integer> phone = new HashMap<>();
 
        for(int i=0; i<nums.length; i++){
            phone.put(nums[i], 1);
        }
        return phone.size() < nums.length/2 ? phone.size() : nums.length/2;     
    } 
}
cs

map은 키값이 중복될 수 없으므로 nums[i]를 키값에 넣고 value에는 어떤 숫자가 들어가도 상관없다.

이러면 자동으로 중복검사가 가능하다.

 

Set

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;
 
class Solution {
    public int solution(int[] nums) {
         
        HashSet<Integer> phone = new HashSet<>();
 
        for(int i=0; i<nums.length; i++){
            phone.add(nums[i]);
        }
        return phone.size() < nums.length/2 ? phone.size() : nums.length/2;     
    } 
}
cs

set 역시 중복값을 받을 수 없으므로 자동 중복검사가 가능하다.