폰켓몬
2023. 1. 29. 19:01ㆍProgrammers/Java
문제
결과
풀이
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 역시 중복값을 받을 수 없으므로 자동 중복검사가 가능하다.
'Programmers > Java' 카테고리의 다른 글
x 사이의 개수 (2) | 2023.05.17 |
---|---|
qr code (2) | 2023.05.13 |
2016년 (2) | 2023.01.29 |
두 개 뽑아서 더하기 (0) | 2023.01.29 |
문자열 내 p와 y의 개수 (0) | 2023.01.21 |