Lumpy Space Princess - Adventure Time
코딩테스트/백준

백준[10816] - 숫자 카드 2

yaebb_82 2023. 5. 9.

 

 

 

문제

 

10816번: 숫자 카드 2

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

www.acmicpc.net

 

 

 

작성한 코드

• 처음 작성한 코드

import sys
input = sys.stdin.readline

N = int(input())
N_list = list(map(int, input().split()))
N_list.sort()

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

for card in M_list:
    lt = 0
    rt = N-1
    count = 0
    isExit = False
    
    while lt<=rt:
        mid = (lt+rt)//2
        
        if card == N_list[mid]:
            isExit = True
            print(N_list.count(card), end=' ')
            break
        elif card > N_list[mid]:
            lt = mid + 1
        else:
            rt = mid - 1

    if not isExit:
        print(0, end=' ')

- 이전 문제(수 찾기)와 동일하게 코드를 작성했는데 시간 초과가 나버렸다.

 

• 다른 사람 풀이

import sys
from collections import Counter
input = sys.stdin.readline

N = int(input())
N_list = list(map(int, input().split()))
N_list.sort()

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

counter = Counter(N_list)

for card in M_list:
    print(counter[card], end=' ')

- 해당 문제를 시간초과 내지 않고 푸는 방법 : dictionary 사용 / Counter 사용 (나는 Counter를 사용해서 풀어보았다.)

- Coutner 함수 : 리스트 내부 원소 갯수를 count 해서 dictionary 형태로 만들어주는 함수

 

 

cf.) counter를 출력해보면 이렇게 나오게 된다.

Counter({10: 3, -10: 2, 3: 2, 2: 1, 6: 1, 7: 1})

 

 

 

반응형

'코딩테스트 > 백준' 카테고리의 다른 글

백준[1920] - 수 찾기  (0) 2023.05.09
백준[2178] - 미로탐색  (0) 2023.03.08
백준[1012] - 유기농 배추  (0) 2023.03.08
백준[2667] - 단지번호붙이기  (0) 2023.03.04
백준[1260] - DFS와 BFS  (0) 2023.03.04

댓글