문제
![](https://velog.velcdn.com/images%2Fcosmos%2Fpost%2F4aadab7d-2f87-4097-95ad-a9f48218e9ea%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202022-02-14%20%E1%84%8B%E1%85%A9%E1%84%8C%E1%85%A5%E1%86%AB%2012.55.26.png)
풀이
- 이분 탐색(이진 탐색) 알고리즘으로 접근하였다.
- 입력 데이터와 탐색 범위가 매우 넓은 편이라
sys
라이브러리의 readline
함수를 이용하여 입력 속도를 줄였다.
- 이진 탐색을 구현하기 위해 탐색할
list
데이터를 sort
한 뒤, 중복된 데이터의 개수를 dict
으로 할당하였다.
- 이후 해당 데이터가 있는지 없는지 이진 탐색으로 하나하나 요소를 확인해가며 체크한 뒤, true false를 반환하도록 구현하였다.
코드
import sys
input = sys.stdin.readline
def solve(array, target, start, end):
while start <= end:
mid = (start+end)//2
if array[mid] == target:
return True
elif array[mid] > target:
end = mid - 1
else:
start = mid + 1
return None
if __name__ == '__main__':
n = int(input())
card_list = sorted(map(int, input().split()))
m = int(input())
sanggeun_list = list(map(int, input().split()))
duplicate_cnt = {}
result = [0] * m
for i in card_list:
if i not in duplicate_cnt:
duplicate_cnt[i] = 1
else:
duplicate_cnt[i] += 1
for x in range(len(sanggeun_list)):
if solve(card_list, sanggeun_list[x], 0, n-1):
result[x] = duplicate_cnt[sanggeun_list[x]]
print(*result)
결과
![](https://velog.velcdn.com/images%2Fcosmos%2Fpost%2Fd1f3ef32-1237-4c5c-9a0c-34e9aff6413f%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202022-02-14%20%E1%84%8B%E1%85%A9%E1%84%8C%E1%85%A5%E1%86%AB%201.34.41.png)
출처 & 깃허브
boj 10816
github