백준 10816번(Python) -숫자 카드 2, 리스트 요소 개수 세기

Jomii·2023년 4월 21일
0

BOJ: Q10816 - 숫자 카드 2 [ 실버 4 ]

문제

숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 몇 개 가지고 있는지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.

셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다. 넷째 줄에는 상근이가 몇 개 가지고 있는 숫자 카드인지 구해야 할 M개의 정수가 주어지며, 이 수는 공백으로 구분되어져 있다. 이 수도 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.

출력

첫째 줄에 입력으로 주어진 M개의 수에 대해서, 각 수가 적힌 숫자 카드를 상근이가 몇 개 가지고 있는지를 공백으로 구분해 출력한다.

예제 입력 1

10
6 3 2 10 10 10 -10 -10 7 3
8
10 9 -5 2 3 4 5 -10

예제 출력 1

3 0 0 1 2 0 0 2

풀이

아래는 시간초과 방식

# 그냥 평소 방식 -> 시간초과 에러
input()
n_lst = list(map(int, input().split()))
input()
m_lst = list(map(int, input().split()))
for i in m_lst:
    print(n_lst.count(i), end=' ')

1) Bisect 라이브러리를 사용하는 방식 (이분탐색)

# 방법 1 : bisect 사용
from bisect import bisect_left, bisect_right
from sys import stdin

n = stdin.readline().rstrip()
n_lst = list(map(int, stdin.readline().split()))
m = stdin.readline().rstrip()
m_lst = list(map(int, stdin.readline().split()))
n_lst.sort()

def count_num(lst, value):
    right_index = bisect_right(lst, value)
    left_index = bisect_left(lst, value)
    return right_index-left_index

for i in m_lst:
    print(count_num(n_lst, i), end=' ')

2) Counter 모듈을 사용하는 방식 (딕셔너리)

# 방법 2 : Counter 사용
from collections import Counter
from sys import stdin

n = stdin.readline().rstrip()
n_lst = list(map(int, stdin.readline().split()))
m = stdin.readline().rstrip()
m_lst = list(map(int, stdin.readline().split()))

count = Counter(n_lst)

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

첫 번째가 counter, 두 번째가 bisect 사용한 방식

해시맵으로도 풀 수 있다고 하는데 아직 공부 안해서...

profile
✉️ qtly_u@naver.com

0개의 댓글