defbinary_search(nums, target):
l =0
r =len(nums)while l < r:
m =(l + r)//2if nums[m]== target:return m
elif nums[m]< target:
l = m +1else:
r = m
return-1
写法2
defbinary_search2(nums, target):
l =0
r =len(nums)-1while l <= r:
m =(l + r)//2if nums[m]== target:return m
elif nums[m]> target:
r = m-1else:
l = m+1return-1
递归
# [begin, end]defbinary_search_rec(nums, begin, end, target):if begin > end:return-1
m =(begin + end)//2if nums[m]== target:return m
elif nums[m]> target:return binary_search_rec(nums, begin, m-1, target)else:return binary_search_rec(nums, m+1, end, target)
lower_bound
# first position >= targetdeflower_bound2(nums, target):
begin =0
end =len(nums)while begin < end:
mid =(begin + end)//2if nums[mid]< target:
begin = mid +1else:
end = mid
return begin
upper_bound
# first position > targetdefupper_bound2(nums, target):
begin =0
end =len(nums)while begin < end:
mid =(begin + end)//2if nums[mid]<= target:
begin = mid +1else:
end = mid
return begin
测试
deftest_binary_search(num, maxnum, times):
nums =[]for _ inrange(num):
nums.append(random.randint(0, maxnum))
nums.sort()for _ inrange(times):
a = random.randint(0, maxnum)
i = nums.index(a)if a in nums else-1
j = binary_search(nums, a)if i != j and nums[j]!= a:print(a, i, j)raise Exception('Error search')
k = binary_search2(nums, a)if k != j and nums[k]!= a:print(a, j, k)raise Exception('Error search2')
l = binary_search_rec(nums,0,len(nums)-1, a)if l != k and nums[l]!= a:print(a, k, l)raise Exception('Error search_rec')deftest_lower_bound(num, maxnum, times):
nums =[]for _ inrange(num):
nums.append(random.randint(0, maxnum))
nums.sort()for _ inrange(times):
a = random.randint(0, maxnum)
i = lower_bound(nums, a)
j = bisect.bisect_left(nums, a)
k = lower_bound2(nums, a)if i != j:raise Exception('Error lower bound')if k != j:raise Exception('Error lower bound2')deftest_upper_bound(num, maxnum, times):
nums =[]for _ inrange(num):
nums.append(random.randint(0, maxnum))
nums.sort()for _ inrange(times):
a = random.randint(0, maxnum)
i = upper_bound(nums, a)
j = bisect.bisect_right(nums, a)
k = upper_bound2(nums, a)if i != j:raise Exception('Error upper bound')if k != j:raise Exception('Error upper bound2')if __name__ =='__main__':
test_binary_search(10000,15000,10000)
test_lower_bound(10000,1500,10000)
test_upper_bound(10000,1500,10000)
test_lower_bound(10000,15000,10000)
test_upper_bound(10000,15000,10000)
二分搜索,lower_bound,upper_bound二分搜索写法1def binary_search(nums, target): l = 0 r = len(nums) while l < r: m = (l + r) // 2 if nums[m] == target: return m ...