Java에서 집합을 표현하는 자료형은 HashSet, TreeSet, LinkedHashSet 등이 있다. Set은 순서가 없고 중복을 허용하지 않음.
HashSet : 중복 없이, 순서 없이 요소 저장. 가장 많이 사용
TreeSet : 중복 없지만 순서가 있는 set
<Method>
add() : 집합에 값 추가 (중복의 경우, 추가 되지 않음)
addAll() : 값을 한번에 여러 개 추가.
remove() : 집합에서 값 제거. 집합에 값이 존재하는 경우 true, 아닌 경우 false 반환
clear() : 집합의 모든 값 제거
contains() : 값이 집합에 존재하면 true, 아니면 false 반환
size() : 집합의 크기, 원소의 개수 반환
<연산>
교집합 : retianAll()
import java.util.*;
public class Main {
public static void main(String[] args) {
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
HashSet<Integer> intersection = new HashSet<>();
intersection.addAll(s1);
intersection.retainAll(s2);
System.out.println(intersection);
}
}
// 출력 : [3, 4, 5]
합집합 : addAll()
import java.util.*;
public class Main {
public static void main(String[] args) {
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
HashSet<Integer> intersection = new HashSet<>(s1);
intersection.addAll(s2);
System.out.println(intersection);
}
}
// 출력 : [1, 2, 3, 4, 5, 6, 7]
차집합 : removeAll()
import java.util.*;
public class Main {
public static void main(String[] args) {
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
HashSet<Integer> intersection = new HashSet<>(s1);
intersection.removeAll(s2);
System.out.println(intersection);
}
}
// 출력 : [1, 2]
[백준 11723] 집합
집합의 기본 메서드를 구현하는 문제
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
HashSet<Integer> set = new HashSet<>();
List<Integer> allList = new ArrayList<>();
for(int i=1; i<=20; i++) {
allList.add(i);
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<m; i++) {
String inputLine = br.readLine();
String[] input = inputLine.split(" ");
if (input[0].equals("add")) {
set.add(Integer.parseInt(input[1]));
}
else if (input[0].equals("remove")) {
set.remove(Integer.parseInt(input[1]));
}
else if (input[0].equals("check")) {
if (set.contains(Integer.parseInt(input[1]))) sb.append(1).append("\n");
else sb.append(0).append("\n");
}
else if (input[0].equals("toggle")) {
int x = Integer.parseInt(input[1]);
if (set.contains(x)) set.remove(x);
else set.add(x);
}
else if (input[0].equals("all")) {
set.clear();
set.addAll(allList);
}
else if (input[0].equals("empty")) {
set.clear();
}
}
System.out.println(sb);
}
}
*) 제한 시간이 1.5초이기 때문에 fastio를 이용해야 한다.
input의 경우 BufferedReader(), StringTokenizer()를 이용하고
output의 경우 StringBuilder()를 이용하여 시간 단축
<참고>
https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html#remove-java.lang.Object-
HashSet (Java Platform SE 8 )
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permi
docs.oracle.com
03-09 집합
집합(Set) 자료형은 집합과 관련된 것을 쉽게 처리하기 위해 만든 것으로 HashSet, TreeSet, LinkedHashSet 등이 있다. 이 중에서 가장 많이 사용하는 H…
wikidocs.net
'개발 언어 > JAVA' 카테고리의 다른 글
| [JAVA/알고리즘] HashSet clear()와 removeAll() 메모리 (백준 1697) (0) | 2025.03.05 |
|---|---|
| [JAVA/알고리즘] 분할 정복 알고리즘 Divide and conquer (백준 2630) (0) | 2025.03.03 |
| [JAVA/알고리즘] 동적 계획법 Dynamic Programming (백준 1463) (0) | 2025.03.01 |
| [JAVA/알고리즘] 매개 변수 탐색 (백준 1654) (0) | 2025.02.26 |
| [Java / 알고리즘] 우선순위 큐 (Priority Queue) (4) | 2025.01.07 |