백준 10816번 숫자 카드2(python)

마뇽미뇽·2025년 3월 11일
0

알고리즘 문제풀이

목록 보기
127/165

1.문제

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

2.풀이

기존에는 2개의 리스트로 만든 후 반복문을 돌리며 조건문으로 만약 값이 있다면 갯수를 출력하도록 했고, 시간초과가 났다.

n = int(input())
card_arr1 = list(map(int, input().split()))

m = int(input())
card_arr2 = list(map(int, input().split()))

for i in card_arr2:
    print(card_arr1.count(i), end=' ')

그래서 찾아보니 counter라는 것이 존재했는데 hash와 같이 항목의 갯수를 셀 때 사용한다고 한다.

3.코드

from collections import Counter

n = int(input())
card_arr1 = list(map(int, input().split()))

m = int(input())
card_arr2 = list(map(int, input().split()))

counter = Counter(card_arr1)

for i in card_arr2:
    if i in counter:
        print(counter[i],end=' ')
    else:
        print(0,end=' ')

4.알게된 점

📚 counter 란? 해시 가능한 객체들을 셀 때 사용하며 각 값들은 딕셔너리에 저장한다. 시간복잡도는 O(n + m)이며 key는 요소 value는 요소의 갯수로 저장된다.

profile
Que sera, sera

0개의 댓글