Zero to Hero
Published 2021. 6. 15. 10:20
lower_bound, upper_bound Algorithm
def lower_bound(input_list, target_value):
    if not input_list:
        return 0
    lo, hi = 0, len(input_list)
    while lo < hi:
        mid = (lo + hi) // 2
        if input_list[mid] < target_value:
            lo = mid + 1
        else:
            hi = mid

    return lo


def upper_bound(input_list, target_value):
    if not input_list:
        return 0
    lo, hi = 0, len(input_list)
    while lo < hi:
        mid = (lo + hi) // 2
        if target_value < input_list[mid]:
            hi = mid
        else:
            lo = mid + 1

    return lo

bisect_left, bisect_right를 그대로 구현한 코드.

직접 구현해야 할 때 헷갈리면 마지막에 lo를 반환하게만 고정하고, hi 이동은 mid로 고정, lo 이동은 mid+1로 고정하는 걸 의식하자.

'Algorithm' 카테고리의 다른 글

131. Palindrome Partitioning  (0) 2021.06.17
105. Construct Binary Tree from Preorder and Inorder Traversal  (0) 2021.06.15
384. Shuffle an Array  (0) 2021.06.14
454. 4Sum II  (0) 2021.06.13
341. Flatten Nested List Iterator  (0) 2021.06.13
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!