Koala - 11기/코딩테스트 준비 스터디

[백준/Python] 숫자카드

happy_life 2023. 8. 4. 13:15

https://www.acmicpc.net/problem/10815

 

10815번: 숫자 카드

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,

www.acmicpc.net

 

 

정답코드

# 숫자 카드
# 복습 횟수:2, 00:10:00, 복습필요X
import sys
si = sys.stdin.readline 

N = int(si())
own_list = list(map(int, si().split()))
own_list.sort()

M = int(si())
check_card_list = list(map(int , si().split()))


def binary_search(check_card):
    start = 0
    end = len(own_list) - 1

    while start <= end:
        mid = (start + end) // 2
        if own_list[mid] == check_card:
            return True
        
        if own_list[mid] > check_card:
            end = mid - 1
        else:
            start = mid + 1

    return False

for check_card in check_card_list:
    if binary_search(check_card):
        print(1, end= " ")
    else:
        print(0, end= " ")

 

 

풀이

1. 전형적인 이분 탐색 문제이다

2. 내가 소유한 것들을 Sort 하고 (O(N))

3. 입력으로 주어진 M개의 수를 차례로 binarySearch 하면 O(M * logN) 의 시간복잡도로 해결할 수 있다.

1 <= N, M <= 500,000이므로  시간 초과가 나지 않는다.

 

 

다른 풀이

dict 에 담아서 O(N)에 풀 수 있다.

 

코드 

# 숫자 카드
# 복습 횟수:2, 00:10:00, 복습필요X
import sys
si = sys.stdin.readline 

N = int(si())
own_list = list(map(int, si().split()))
own_list.sort()

M = int(si())
check_card_list = list(map(int , si().split()))

own_dict = dict()

for own in own_list:
    if own not in own_dict.keys():
        own_dict[own] = 1


for check_card in check_card_list:
    if check_card in own_dict.keys():
        print(1, end = " ")
    else:
        print(0, end = " ")