자료구조&알고리즘/백준

백준 | [파이썬 Python] 10816 숫자 카드 2

두잇 두두 2024. 5. 28. 22:41
728x90

배경

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

 

 

 

코드

import sys
input = sys.stdin.readline

N = int(input())
cards = sorted([*map(int, input().split())])
M = int(input())
candidate = [*map(int, input().split())]

count = dict()
for card in cards:
    if count.get(card, False):
        count[card] += 1
    else:
        count[card] = 1

def binarySearch(arr, target, start, end):
    if start > end:
        return 0
    
    mid = (start + end) // 2
    if arr[mid] == target:
        return count.get(target)
    elif arr[mid] < target:
        return binarySearch(arr, target, mid+1, end)
    else:
        return binarySearch(arr, target, start, mid-1)
    
for target in candidate:
    print(binarySearch(cards, target, 0, len(cards)-1), end=" ")

 

 

설명

헷갈렸던 점 => 이분 탐색을 하는 이유는 cards 안에 해당 target이 있는 지 확인하기 위함이다

 

 

배운 점