Algorithm/Baekjoon
[백준] Python - 10816 숫자 카드 2
aldrn29
2022. 8. 17. 18:57
문제 링크
https://www.acmicpc.net/problem/10816
10816번: 숫자 카드 2
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,
www.acmicpc.net
문제 풀이
처음에는 상근이가 가지고 있는 숫자 카드 리스트의 개수를 count 함수를 사용하여 구하려 하였지만, 시간 초과가 발생했다. 그래서 알게된 것이 Counter 모듈이다. 또 다른 풀이 방법으로 Dictionary를 사용하여 개수를 카운트 해주었다.
1. Counter
2. Dictionary
전체 코드
1. Counter 사용
from collections import Counter
import sys
input = sys.stdin.readline
n = int(input()) # 상근이가 가지고 있는 숫자 카드 개수
nums = list(map(int, input().split()))
m = int(input())
check_nums = map(int, input().split())
cards = Counter(nums)
result = []
for i in check_nums:
result.append(cards[i])
print(*result)
2. Dictionary 사용
from collections import defaultdict
import sys
input = sys.stdin.readline
n = int(input()) # 상근이가 가지고 있는 숫자 카드 개수
nums = list(map(int, input().split()))
m = int(input())
check_nums = map(int, input().split())
dic = defaultdict(int)
for i in nums :
dic[i] += 1
for i in check_nums :
if i in dic :
print(dic[i], end=' ')
else :
print(0, end=' ')
시간 초과된 코드
더보기
import sys
input = sys.stdin.readline
n = int(input()) # 상근이가 가지고 있는 숫자 카드 개수
nums = list(map(int, input().split()))
m = int(input())
check_nums = map(int, input().split())
for x in check_nums :
print(nums.count(x), end=' ')