PS/Python
[Python] 백준 10816번(숫자 카드 2) 문제 풀이
KwonYongHyeon
2022. 7. 30. 19:01
import collections
def binary_search(nums, target):
left, right = 0, len(nums)-1
while left <= right:
mid = (left+right) // 2
if nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
else:
return 1
return 0
input()
have = sorted(list(map(int, input().split(" "))))
have_collection = collections.Counter(have)
input()
cards = list(map(int, input().split(" ")))
for i in cards:
if binary_search(have, i) == 0:
print(0, end=" ")
continue
else:
print(have_collection[i], end=" ")
이진 탐색 알고리즘과 collections.Counter() 함수를 이용해서 만들었다. collections.Counter() 함수는 리스트 내에 들어 있는 요소의 수를 딕셔너리 형태로 반환한다. 예를 들어서, [1, 3, 3, 3, 2, 2]를 {1: 1, 3: 3, 2: 2}의 형태로 주는 식.