Post

[백준] 10815번 - 숫자 카드 [Java][C++]

[백준] 10815번 - 숫자 카드 [Java][C++]

문제 링크


1. 문제 풀이

$N$ 이 최대 $500,000$ 이고 각 숫자가 $-10,000,000 \sim 10,000,000$ 일 때, $M$ 개의 숫자에 대해 등장한 적이 있는지 여부를 출력하는 문제다. 가장 간단하게는 집합을 활용해 등장 여부를 판단할 수 있고, 주어진 숫자 카드를 정렬한 후 이분 탐색을 통해 등장했는지 판단하는 방식으로 해결할 수 있다. 주어진 수의 범위가 크긴 하지만 인덱스와 숫자를 매핑한 방문 체크 배열을 통해서도 해결할 수 있다.


2. 코드

1. 이분 탐색 [Java]

Arrays.binarySearch 메서드를 활용했고 주어진 배열에 존재하지 않으면 $-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
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;

        int N = Integer.parseInt(br.readLine());

        int[] arr = new int[N];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(arr);

        br.readLine();
        st = new StringTokenizer(br.readLine());
        while (st.hasMoreTokens()) {
            if (Arrays.binarySearch(arr, Integer.parseInt(st.nextToken())) >= 0) {
                sb.append("1 ");
            } else {
                sb.append("0 ");
            }
        }

        System.out.println(sb);
    }
}

2. 방문 체크 [Java]

음수 범위도 커버해야 해서 앞에 음수 범위만큼의 패딩을 주어 $-10,000,000$ 이 인덱스 $0$ 에 매핑되도록 했다.

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
import java.io.*;
import java.util.*;

public class Main {

    static final int MAX = 10_000_000;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;

        br.readLine();
        boolean[] visited = new boolean[MAX + 1 + MAX];
        st = new StringTokenizer(br.readLine());
        while (st.hasMoreTokens()) {
            visited[Integer.parseInt(st.nextToken()) + MAX] = true;
        }

        br.readLine();
        st = new StringTokenizer(br.readLine());
        while (st.hasMoreTokens()) {
            if (visited[Integer.parseInt(st.nextToken()) + MAX]) {
                sb.append("1 ");
            } else {
                sb.append("0 ");
            }
        }

        System.out.println(sb);
    }
}

3. 해시를 사용한 집합과 맵 [Java]

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
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;

        Set<Integer> set = new HashSet<>();

        br.readLine();
        st = new StringTokenizer(br.readLine());
        while (st.hasMoreTokens()) {
            set.add(Integer.parseInt(st.nextToken()));
        }

        br.readLine();
        st = new StringTokenizer(br.readLine());
        while (st.hasMoreTokens()) {
            if (set.contains(Integer.parseInt(st.nextToken()))) {
                sb.append("1 ");
            } else {
                sb.append("0 ");
            }
        }

        System.out.println(sb);
    }
}

4. 이분 탐색 [C++]

찾으면 true, 못 찾으면 false 를 반환하는 binary_search 함수를 활용했다.

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
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<int> v(n);
    for (int& x : v) cin >> x;
    sort(v.begin(), v.end());

    int m;
    cin >> m;

    for (int i = 0; i < m; i++) {
        int x;
        cin >> x;

        if (binary_search(v.begin(), v.end(), x)) {
            cout << "1 ";
        } else {
            cout << "0 ";
        }
    }
}

5. 방문 체크 [C++]

음수 범위도 커버해야 해서 앞에 음수 범위만큼의 패딩을 주어 $-10,000,000$ 이 인덱스 $0$ 에 매핑되도록 했다.

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
#include <bits/stdc++.h>
using namespace std;

constexpr int MAX = 10000000;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<bool> visited(MAX + 1 + MAX);
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;

        visited[x + MAX] = true;
    }

    int m;
    cin >> m;

    for (int i = 0; i < m; i++) {
        int x;
        cin >> x;

        if (visited[x + MAX]) {
            cout << "1 ";
        } else {
            cout << "0 ";
        }
    }
}

6. 해시를 사용한 집합과 맵 [C++]

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
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    unordered_set<int> st;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;

        st.insert(x);
    }

    int m;
    cin >> m;

    for (int i = 0; i < m; i++) {
        int x;
        cin >> x;

        if (st.count(x)) {
            cout << "1 ";
        } else {
            cout << "0 ";
        }
    }
}

3. 풀이 정보

1. 이분 탐색 [Java]

언어시간메모리코드 길이
Java 111280 ms106012 KB887 B

2. 방문 체크 [Java]

언어시간메모리코드 길이
Java 11756 ms112876 KB1895000 B

3. 해시를 사용한 집합과 맵 [Java]

언어시간메모리코드 길이
Java 11924 ms137888 KB829 B

4. 이분 탐색 [C++]

언어시간메모리코드 길이
C++ 17256 ms3976 KB459 B

5. 방문 체크 [C++]

언어시간메모리코드 길이
C++ 17140 ms4464 KB535 B

6. 해시를 사용한 집합과 맵 [C++]

언어시간메모리코드 길이
C++ 17372 ms23304 KB474 B

This post is licensed under CC BY 4.0 by the author.