주어진 폰켓몬 목록에서 최대한 다양한 종류의 폰켓몬을 선택하는 문제. 아래의 2 숫자를 구하고, 더 작은 값이 결과가 된다.
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int solution(int[] nums) {
// 1. 폰켓몬 종류를 저장할 Set 생성
Set<Integer> uniquePokemens = new HashSet<>();
// 2. 배열을 순회하며 Set에 폰켓몬 종류 추가
for (int num : nums) {
uniuePokemons.add(num);
}
// 3. 선택 가능한 최대 폰켓몬 수 계산
int maxSelectable = nums.length / 2;
// 4. Set의 크기와 maxSelectble 중 작은 값을 반환
return Math.min(uniquePokemeons.size(), maxSelectable);
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {3, 1, 2, 3};
System.out.println(sol.solution(nums)); // 출력: 2
}
HashSet
java.util
패키지에 포함된 컬렉션 클래스 중 하나.set.add(3);
set.remove(3);
boolean exist = set.contains(3);
int size = set.size()
boolean isEmpty =set.isEmpty()
set.clear();
HashSe
t은 내부적으로 해시 테이블을 사용해 데이터를 저장하고 관리한다. 이를 통해 빠른 검색, 추가, 삭제 작업이 가능하다.
hashCode()
메서드를 호출하여 해당 요소의 해시 값을 계산한다.HashSet
은 이를 처리하기 위해 체이닝(chaining) 또는 오픈 어드레싱(open addressing) 등의 방법을 사용한다. 자바의 HashSet
은 체이닝을 사용하여 각 버킷에 연결 리스트(linked list)또는 트리(tree) 형태로 요소를 저장한다.import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// 요소 추가
set.add("apple");
set.add("banana");
set.add("cherry");
// 중복된 요소 추가 시 무시됨
set.add("apple");
// 요소 출력
System.out.println(set); // [banana, cherry, apple] (순서는 다를 수 있음)
// 요소 검색
System.out.println(set.contains("banana")); // true
System.out.println(set.contains("grape")); // false
// 요소 삭제
set.remove("banana");
System.out.println(set); // [cherry, apple]
}
}