boj10816-숫자카드2

먼지감자·2021년 6월 5일
0

코딩테스트

목록 보기
10/37

문제 : 숫자카드2
주어진 리스트 안에 특정 숫자가 몇개 있는지 찾는 문제

  • 풀이 1
import sys
from bisect import bisect_left, bisect_right

if __name__ == '__main__':
    input = sys.stdin.readline

    N = int(input())
    card = sorted(list(map(int, input().split())))
    M = int(input())
    M_list = list(map(int, input().split()))

    for m in M_list:
        lower_bound = bisect_left(card, m)
        upper_bound = bisect_right(card, m)
        print(upper_bound-lower_bound)

--> 이진탐색 이용
bisect_left : 정렬된 리스트에서 주어진 숫자가 들어갈 수있는 가장 작은 인덱스 반환 = lower bound
bisect_right : 정렬된 리스트에서 주어진 숫자가 들어갈 수있는 가장 큰 인덱스 반환 = upper bound

from sys import stdin

N = int(input())
arr_n = list(map(int,stdin.readline().split()))
M = int(input())
arr_m = list(map(int,stdin.readline().split()))

dic = dict()

for i in arr_n:
    try :
        dic[i] += 1
    except:
        dic[i] = 1

for i in arr_m:
    try:
        print(dic[i])
    except:
        print('0')

--> 계수정렬 이용
dictionary 이용하여 숫자 = key로 두고 개수를 value로 저장
try except 문 사용하여 key 가 이미 있으면 +1 , 없으면 1로 초기화

profile
ML/AI Engineer

0개의 댓글