Algorithm/BOJ
[백준/10815] 숫자 카드 (with 파이썬)
Potato potage
2022. 11. 30. 14:17
반응형
✔ 문제
✔ 풀이
😥 시간 초과
import sys
input = sys.stdin.readline
n = int(input())
n_cards = list(map(int, input().split()))
m = int(input())
m_cards = list(map(int, input().split()))
res = [0] * m
for i in range(m):
if m_cards[i] in n_cards:
res[i] = 1
print(*res)
🥺 정답 코드
import sys
input = sys.stdin.readline
n = int(input())
n_cards = list(map(int, input().split()))
m = int(input())
check = list(map(int, input().split()))
dict = {} # dictionary 생성
for i in range(n):
dict[n_cards[i]] = 0
for j in range(m):
if check[j] not in dict:
print(0, end=' ')
else:
print(1, end=' ')
✔ 설명
1. check 배열에 있는 수들이 n_cards에 있는지 확인 하는 작업이기 때문에 n_cards의 값을 dict의 key값으로 저장한다.
2. check 배열 길이만큼 for문을 돌려 check 배열에 있는 값이 dict에 없다면 0을, 있다면 1을 출력하도록 한다.
✔ 후기
해당 문제는 for문으로 풀면 시간초과가 난다.
다른 분들 블로그를 참고해보면 dictionary나 이진 탐색으로 푸는데 이진 탐색은 뒤에서 따로 풀기 때문에 dictionary로 풀어봤다.
반응형