Chapter 6: Sorting and Searching

# 知识解析

这里参照 Ruby 中 bsearch_index 的实现,take一个 function 作为参数表示需要满足的条件,找到满足条件的最小index和最大index(注意这一条件对 bsearch_low 必须是“单调递增“,对 bsearch_high 必须是“单调递减“)。

如果寻找的是具体的一个target值,需要传入 lambda ele: ele >= targetlambda ele: ele <= target 在找到index的上下限之后需要额外一步检查来确定是否能找到。

"""
condition should be a function that evaluates as
[False, False ... True, True, True], aka >= target
"""


def bsearch_low(arr: List[int], condition: Callable[[int], bool]) -> Optional[int]:
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2  
        smaller = condition(arr[mid])
        if smaller:
            high = mid - 1
        else:
            low = mid + 1

    if low >= len(arr) or not condition(arr[low]):
        return None

    return low


"""
condition should be a function that evaluates as
[True, True ... False, False, False], aka <= target
"""


def bsearch_high(arr: List[int], condition: Callable[[int], bool]) -> Optional[int]:
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2  
        bigger = condition(arr[mid])
        if bigger:
            low = mid + 1
        else:
            high = mid - 1

    if high < 0 or not condition(arr[high]):
        return None

    return high

e.g. 1 Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. ( LeetCode: Find First and Last Position of Element in Sorted Arrayarrow-up-right )

e.g.2 We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime , endTime and profit arrays, you need to output the maximum profit you can take such that there are no 2 jobs in the subset with overlapping time range.( LeetCode: Maximum Profit in Job Schedulingarrow-up-right)

Last updated