[백준] 숫자 카드 2 10816번

나의 풀이

N = int(input())
nums = sorted(map(int, input().split()))
M = int(input())
cards = list(map(int, input().split()))
result = [0] * M
def binary_search(arr, target, start, end, idx):
    while start <= end:
        mid = (start + end) // 2
        if arr[mid] == target:
            result[idx] += 1
            arr.pop(mid)
            return binary_search(arr, target, start, len(arr) - 1, idx)
        elif arr[mid] > target:
            end = mid - 1
        elif arr[mid] < target:
            start = mid + 1
    return None

for i in range(len(cards)):
    binary_search(nums, cards[i], 0, len(nums) - 1, i)

print(*result)
  • 나의 첫 풀이
  • 이진 탐색을 구현하여 중복되는 카드의 숫자를 찾기위해 재귀를 돌려서 찾지 못할 때까지 탐색하였다.
  • 테스트코드 예제는 맞았으나 자꾸 실패하였다. 원인을 모르겠다.

다른 사람 풀이 & 느낀점

간단하게 함수형 자료구조를 이용하여 풀 수 있다.

N = int(input())
n_cards = list(map(int, input().split()))
M = int(input())
m_cards = list(map(int, input().split()))
dictionary = {}

for i in n_cards:
    dictionary[i] = dictionary.get(i, 0) + 1

for i in m_cards:
    if i in dictionary:
        print(dictionary[i], end=" ")
    else:
        print(0, end=" ")
  • 위와 같이 값을 받고 빈 딕셔너리를 하나 만들어준다.
  • 여기에 n_cards 의 숫자를 키 값으로 사용하고, 해당 키 값이 비어있으면 0 을 기본 값으로 세팅하고 +1 을 추가한다.
  • 그리고 m_cards 를 돌면서 딕셔너리의 키 중에서 해당 카드번호와 일치하는 키가 있다면 해당 키의 밸류를 출력해주고, 아니면 0을 출력해준다.

dictionary.get(i, 0) -> 해당 키 값이 밸류를 가지고 있지 않으면 0으로 세팅한다.

0개의 댓글