문제
프로그래머스 [포켓몬]
문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/1845
해결 방법
- HashSet을 사용하여 nums 배열에 있는 모든 폰켓몬 번호를 중복 없이 저장한다.
- maxSelect 변수에 N/2 값을 저장한다. -> 선택 가능한 폰켓몬 수의 최대치이다.
- Math.min(set.size(), maxSelect)를 사용하여 선택 가능한 폰켓몬 종류의 최대 개수를 계산한다.
- 종류 수가 선택 가능한 수를 초과하는 경우, 작은 값을 반환한다.
코드
import java.util.HashSet;
class Solution {
public int solution(int[] nums) {
// 1. 중복 없는 폰켓몬 종류의 개수를 구하기 위해 HashSet 사용
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
// 2. 최대 선택 가능한 폰켓몬 수 계산
int maxSelect = nums.length / 2;
// 3. 결과는 폰켓몬 종류 수와 maxSelect 중 작은 값을 반환
return Math.min(set.size(), maxSelect);
}
}
- 참고할 다른 풀이 방법
더보기
- 스트림
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)));
}
}
import java.util.HashMap;
class Solution {
public int solution(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < nums.length; i++)
map.put(nums[i], 1);
return map.size() > nums.length / 2 ? nums.length / 2 : map.size();
}
}
'개발 공부 > 코딩테스트' 카테고리의 다른 글
99클럽 코테 스터디 12일차 TIL - 스택 (0) | 2024.11.08 |
---|---|
99클럽 코테 스터디 11일차 TIL - 해시 (1) | 2024.11.08 |
99클럽 코테 스터디 9일차 TIL - 문자열, 해시 (0) | 2024.11.05 |
99클럽 코테 스터디 8일차 TIL - 해시 (0) | 2024.11.05 |
99클럽 코테 스터디 5일차 TIL - 해시 (0) | 2024.11.01 |