[백준] 1920번 - 수 찾기

야금야금 공부·2023년 4월 29일
0

백준

목록 보기
27/52

https://www.acmicpc.net/problem/1920

문제

N개의 정수 A[1], A[2], …, A[N]이 주어져 있을 때, 이 안에 X라는 정수가 존재하는지 알아내는 프로그램을 작성하시오.

입력

첫째 줄에 자연수 N(1N100,000)N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1M100,000)M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들이 A안에 존재하는지 알아내면 된다. 모든 정수의 범위는 231-2^{31} 보다 크거나 같고 2312^{31}보다 작다.

출력

M개의 줄에 답을 출력한다. 존재하면 1을, 존재하지 않으면 0을 출력한다.



문제 풀이

  • 처음에는 list를 사용하였으나 시간 초과 발생
    - list의 search는 O(n)O(n)이다.
  • set의 search는 O(1)O(1)
import sys
input = sys.stdin.readline

n = int(input())
nlist = set(map(int, input().split()))

m = int(input())
mlist = list(map(int, input().split()))

for i in mlist:
    if i in nlist:
        print(1)
    else:
        print(0)

이분 탐색으로 풀이

def binary_search(target, data, start, end):
    if start > end:
        return 0

    mid = (start + end) // 2

    if data[mid] == target:
        return 1
    elif data[mid] > target:
        end = mid - 1
    else:
        start = mid + 1

    return binary_search(target, data, start, end)


n = int(input())
nlist = set(map(int, input().split()))
nlist = sorted(nlist)

m = int(input())
mlist = list(map(int, input().split()))

for i in mlist:
    print(binary_search(i, nlist, 0, len(nlist)-1))

참고 자료

0개의 댓글