python實現的lower_bound和upper_bound

1. lower_bound(nums, target)

在非遞減數組nums中,lower_bound(nums, target)返回第一個大於等於target的值得位置,如果nums中元素均小於target(即不存在>=target的元素),則返回nums的長度(即target如果要插入到nums中,應該插入的位置)

#coding=utf-8
#返回nums中第一個>=target的值得位置,如果nums中都比target小,則返回len(nums)
def lower_bound(nums, target):
    low, high = 0, len(nums)-1
    pos = len(nums)
    while low<high:
        mid = (low+high)/2
        if nums[mid] < target:
            low = mid+1
        else:#>=
            high = mid
            pos = high
    return pos
測試

nums = [10, 10, 10, 20, 20, 20, 30, 30]   
print lower_bound(nums, 9),
print lower_bound(nums, 10),
print lower_bound(nums, 15),
print lower_bound(nums, 20),
print lower_bound(nums, 25),
print lower_bound(nums, 30),
print lower_bound(nums, 40)
運行結果:


2. upper_bound(nums, target)

在非遞減數組nums中,upper_bound(nums, target)返回第一個大於target的值位置,如果nums中元素均小於等於target(即不存在>target的元素),則返回nums的長度(即target如果要插入到nums中,應該插入的位置)

#返回nums中第一個>target的值得位置,如果nums中都不比target大,則返回len(nums)
def upper_bound(nums, target):
    low, high = 0, len(nums)-1
    pos = len(nums)
    while low<high:
        mid=(low+high)/2
        if nums[mid]<=target:
            low = mid+1
        else:#>
            high = mid
            pos = high
    return pos
測試:

nums = [10, 10, 10, 20, 20, 20, 30, 30] 
print upper_bound(nums, 9),
print upper_bound(nums, 10),
print upper_bound(nums, 15),
print upper_bound(nums, 20),
print upper_bound(nums, 25),
print upper_bound(nums, 30),
print upper_bound(nums, 40)
運行結果:



c++ lower_bound源碼參考:http://www.cplusplus.com/reference/algorithm/lower_bound/

c++ upper_bound源碼參考:http://www.cplusplus.com/reference/algorithm/upper_bound/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章