본문 바로가기
Beakjoon&프로그래머스/파이썬

[백준/파이썬] 11663번 선분 위의 점

by 현장 2022. 5. 6.

-Code

from sys import stdin

def binary(l, arr, target):
    start = 0
    end = l - 1
    while start < end:
        mid = (start + end) // 2
        if target < arr[mid]:
            end = mid - 1
        elif target > arr[mid]:
            start = mid + 1
        else:
            return mid
    return start


n, m = map(int, stdin.readline().split())
points = sorted(list(map(int, stdin.readline().split())))
for _ in range(m):
    low, high = map(int, stdin.readline().split())

    low_idx = binary(n, points, low)
    S = low_idx if points[low_idx] >= low else low_idx + 1

    high_idx = binary(n, points, high)
    E = high_idx if points[high_idx] <= high else high_idx - 1

    print(E - S + 1)

처음에 코드를 작성했으나 리스트에 존재하지 않는 값일 경우 문제가 생겨서 if문을 계속 바꿔주었으나 해결이 되지 않아 문제를 찾아보니 시작 지점과 끝나는 지점 각각 if문을 해주지 않아서 문제가 생긴 거였습니다.