수학 - HashSet의 교집합
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 30번째.
두 집합의 교집합은 두 집합에 모두 존재하는 요소만 포함하는 새로운 집합입니다. Java에서는 retainAll() 메서드를 사용하여 교집합을 계산할 수 있습니다.
먼저, 두 개의 새로운 HashSet을 생성하세요:
HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);이 새로운 집합은 첫 번째 집합의 모든 요소로 시작합니다.
HashSet<Integer> intersectionSet = new HashSet<>(set1);다음으로, 두 번째 집합에도 있는 요소들만 유지하세요:retainAll() 메서드를 사용하세요.
intersectionSet.retainAll(set2);
System.out.println("Intersection: " +
intersectionSet);
// Output: [2]챌린지
쉬움<strong>intersectionSets</strong>라는 이름의 메서드를 생성하세요. 이 메서드는 정수의 HashSet 두 개를 입력으로 받아 교집합을 계산하고 다음 형식으로 출력해야 합니다:
Intersection: [2]
치트 시트
두 집합의 교집합은 두 집합에 모두 존재하는 요소만 포함합니다. 교집합을 계산하기 위해 retainAll()을 사용하세요:
HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);
// Create new set with elements from first set
HashSet<Integer> intersectionSet = new HashSet<>(set1);
// Retain only elements that are also in second set
intersectionSet.retainAll(set2);
System.out.println("Intersection: " + intersectionSet);
// Output: [2]직접 해보기
import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Main {
public static void intersectionSets(HashSet<Integer> set1, HashSet<Integer> set2) {
// 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 첫 번째 집합을 위한 JSON 문자열 읽기 (예: [1,2])
String set1String = scanner.nextLine();
// 두 번째 집합을 위한 JSON 문자열 읽기 (예: [2,3])
String set2String = scanner.nextLine();
Type setType = new TypeToken<HashSet<Integer>>(){}.getType();
HashSet<Integer> set1 = new Gson().fromJson(set1String, setType);
HashSet<Integer> set2 = new Gson().fromJson(set2String, setType);
intersectionSets(set1, set2);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.