function for finding last item less-than-or-equal to, like lower_bound

前端 未结 5 1747
南方客
南方客 2021-01-30 12:52

Is there a function in that uses binary search, like lower_bound but that returns the last item less-than-or-equal-to according to a given predic

5条回答
  •  终归单人心
    2021-01-30 13:44

    A simple implementation in Python:

    def bi_search(arr, target):
        """
        index of the last element which <= target
        """
    
        lo, hi = 0, len(arr)
        while lo < hi:
            mid = lo + (hi - lo) // 2
            if arr[mid] <= target:
                lo = mid + 1
            else:
                hi = mid
        return lo - 1
    

提交回复
热议问题