[伯俊-python]1920個の数字を検索



バイナリナビゲーションの問題
https://www.fun-coding.org/Chapter16-binarysearch.html

初めての試み

#coding:utf8
# 수 찾기

from sys import stdin

N = int(stdin.readline())
NList = map(int, stdin.readline().split())
M = int(stdin.readline())
MList = map(int, stdin.readline().split())

for m in MList:
    if m in NList:
        print(1)
    else:
        print(0)

中間試行

#coding:utf8
# 수 찾기

from sys import stdin

N = int(stdin.readline())
NList = sorted(map(int, stdin.readline().split()))
M = int(stdin.readline())
MList = map(int, stdin.readline().split())


def binary_search(searchList, target):
    if len(searchList) == 1:
        if searchList[0] == target:
            return 1
        else:
            return 0
    if searchList == []:
        return 0

    mid = len(searchList) // 2
    if target == searchList[mid]:
        return 1
    if target > searchList[mid]:
        return binary_search(searchList[mid:], target)
    else:
        return binary_search(searchList[:mid], target)

for m in MList:
    print(binary_search(NList, m))

最終正解

#coding:utf8
# 수 찾기

from sys import stdin

N = int(stdin.readline())
NList = sorted(map(int, stdin.readline().split()))
M = int(stdin.readline())
MList = map(int, stdin.readline().split())


def binary_search(searchList, target, startIndex, endIndex):
    if startIndex > endIndex:
        return 0

    mid = (startIndex+endIndex) // 2
    if target == searchList[mid]:
        return 1
    if target > searchList[mid]:
        return binary_search(searchList, target, mid+1,endIndex)
    else:
        return binary_search(searchList, target, startIndex, mid-1)

for m in MList:
    startIndex = 0
    endIndex = N-1
    print(binary_search(NList, m, startIndex, endIndex))