교육/알고리즘_기본

📌 자료구조 : Set, Map

Jedy_Kim 2024. 7. 18. 16:24
728x90

🎯 Set

**집합(Set)**은 중복되지 않는 원소들의 모음.

수학에서의 집합 개념을 차용한 자료구조로, 주로 원소의 중복을 허용하지 않고, 순서가 중요하지 않은 경우에 사용.

중복 불허: 동일한 원소가 두 개 이상 존재할 수 없음.

순서 없음: 원소들 간에 순서가 존재하지 않음.

빠른 탐색: 일반적으로 탐색, 삽입, 삭제의 시간 복잡도가 평균적으로 O(1).

 

- 아래 예제를 이해하면서 타이핑 해볼 것.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.HashSet;
import java.util.Set;
 
public class DataStructures {
 
    public static void ExamSet() {
        // Set 생성
        Set<Integer> mySet = new HashSet<>();
 
        // 원소 추가
        mySet.add(1);
        mySet.add(2);
        mySet.add(3);
        mySet.add(4);
        mySet.add(5);
 
        // 중복된 원소 추가 시도
        mySet.add(3);  // Set은 중복을 허용하지 않으므로 추가되지 않음
 
        // Set 출력
        System.out.println("Set: " + mySet);  // [1, 2, 3, 4, 5]
 
        // 원소 삭제
        mySet.remove(4);
 
        // Set 출력
        System.out.println("Set after removal: " + mySet);  // [1, 2, 3, 5]
 
        // 탐색
        boolean containsTwo = mySet.contains(2);
        System.out.println("Set contains 2: " + containsTwo);  // true
 
        boolean containsFour = mySet.contains(4);
        System.out.println("Set contains 4: " + containsFour);  // false
 
        // Set 크기
        int setSize = mySet.size();
        System.out.println("Set size: " + setSize);  // 4
 
        // 다른 Set 생성
        Set<Integer> anotherSet = new HashSet<>();
        anotherSet.add(3);
        anotherSet.add(4);
        anotherSet.add(5);
        anotherSet.add(6);
 
        // 합집합 (Union)
        Set<Integer> unionSet = new HashSet<>(mySet);
        unionSet.addAll(anotherSet);
        System.out.println("Union of sets: " + unionSet);  // [1, 2, 3, 4, 5, 6]
 
        // 교집합 (Intersection)
        Set<Integer> intersectionSet = new HashSet<>(mySet);
        intersectionSet.retainAll(anotherSet);
        System.out.println("Intersection of sets: " + intersectionSet);  // [3, 5]
 
        // 차집합 (Difference)
        Set<Integer> differenceSet = new HashSet<>(mySet);
        differenceSet.removeAll(anotherSet);
        System.out.println("Difference of sets: " + differenceSet);  // [1, 2]
 
        // 대칭 차집합 (Symmetric Difference)
        Set<Integer> symmetricDifferenceSet = new HashSet<>(mySet);
        symmetricDifferenceSet.addAll(anotherSet);
        Set<Integer> tempSet = new HashSet<>(mySet);
        tempSet.retainAll(anotherSet);
        symmetricDifferenceSet.removeAll(tempSet);
        System.out.println("Symmetric Difference of sets: " + symmetricDifferenceSet);  // [1, 2, 4, 6]
    }
 
    public static void main(String[] args) {
        ExamSet();
    }
 
}
cs

🎯 Map

**맵(Map)**은 키(key)와 값(value)의 쌍을 저장하는 자료구조.

다른 언어에서는 해시맵(HashMap)이나 사전(Dictionary)이라고도 불림.

주로 키를 통해 값을 빠르게 검색, 삽입, 삭제하는 데 사용됨.

키-값 쌍: 각 키는 고유하며, 하나의 키는 하나의 값과 연결됨.

빠른 접근: 키를 사용하여 값을 빠르게 검색할 수 있습니다. 평균적으로 탐색, 삽입, 삭제의 시간 복잡도는 O(1).

무순서: 키-값 쌍은 특정 순서를 가지지 않는다. (단, 일부 구현체는 순서를 유지하기도 함.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.HashMap;
import java.util.Map;
 
public class DataStructures {
 
    public static void ExamMap() {
        // Map 생성
        Map<String, Integer> map = new HashMap<>();
 
        // 키-값 쌍 추가
        map.put("apple"1);
        map.put("banana"2);
        map.put("cherry"3);
 
        // 키를 통해 값 검색
        int value = map.get("banana");
        System.out.println("Value for key 'banana': " + value);  // 2
 
        // 존재 확인
        boolean hasApple = map.containsKey("apple");
        System.out.println("Map contains key 'apple': " + hasApple);  // true
 
        boolean hasGrape = map.containsKey("grape");
        System.out.println("Map contains key 'grape': " + hasGrape);  // false
 
        // 키-값 쌍 삭제
        map.remove("cherry");
 
        // 맵 크기 확인
        int size = map.size();
 
    }
 
    public static void main(String[] args) {
        ExamMap();
    }
 
}
cs

 

🎯 과제

1) Set - 실습(1)

https://school.programmers.co.kr/learn/courses/9/lessons/404

2) Map - 완주하지 못한 선수

https://school.programmers.co.kr/learn/courses/30/lessons/42576

반응형

'교육 > 알고리즘_기본' 카테고리의 다른 글

📌 기본 정렬(선택, 삽입, 버블)  (0) 2024.07.30
📌 문자열  (0) 2024.07.25
📌 재귀함수  (0) 2024.07.18
📌 배열(개념)  (0) 2024.07.11
📌 자료구조 : 스택, 큐, 덱  (0) 2024.07.01