백준_10816 (숫자 카드2_이진탐색 써야하는 이유)

RostoryT·2022년 6월 19일
0

Binary Search

목록 보기
2/8

메모

  • Counter 라이브러리 사용하자

  • 앞서 풀었던 것처럼 set사용하면 안된다

    • 이유 : set은 중복제거되기 때문에, 이 문제처럼 개수 세는 문제에선 쓰면 안된다!

이진탐색 안쓴 ver.

  • collections의 Counter 사용
    - Counter()를 쓰게되면 다음과 같은 결과({key : count})형태로 반환
    • Counter.get(키값)을 쓰면 해당 key값의 value를 반환
  • 이진탐색을 썼을 때보다 속도가 느릴 줄 알았는데, 더 빠르다고 하여 놀랐다.
from collections import Counter

n = int(input())
arr = list(map(int,input().split()))
m = int(input())
card_list = list(map(int, input().split()))

c = Counter(arr)
ans = []

for card in card_list:
    ans.append(c.get(card)) if card in c else ans.append(0)

print(*ans)



Counter 코드 더 짧게

from collections import Counter

_ = int(input())
arr = list(map(int,input().split()))
_ = int(input())
card_list = list(map(int, input().split()))

C = Counter(arr)
print(' '.join(f'{C[card]}' if card in arr else '0' for card in card_list))

profile
Do My Best

0개의 댓글