코딩테스트/BOJ

[백준 1920] [이분 탐색] 수 찾기

박소민 2022. 9. 17. 13:00
수 찾기




다른 사람 풀이
이분 탐색 기본

N = int(input())
A = list(map(int, input().split()))
m = int(input())
num= list(map(int, input().split()))
A.sort()			# A 정렬

# arr의 각 원소별로 이분탐색
for n in num:
    lt, rt = 0, N - 1		# lt는 맨 앞, rt는 맨 뒤
    isExist = False		# 찾음 여부

    # 이분탐색 시작
    while lt <= rt:		# lt가 rt보다 커지면 반복문 탈출
        mid = (lt + rt) // 2	# mid는 lt와 rt의 중간값
        if n == A[mid]:	# num(목표값)이 A[mid]값과 같다면 (목표값 존재여부를 알았다면)
            isExist = True	# isExist Ture 변경
            print(1)		# 1 출력
            break		# 반복문 탈출
        elif n > A[mid]:	# A[mid]가 num보다 작으면
            lt = mid + 1	# lt를 높임
        else:			# A[mid]가 num보다 크다면
            rt = mid - 1	# rt를 낮춤

    if not isExist:		# 찾지 못한 경우
        print(0)		# 0 출력