二分查找万能模板-python
由九章算法-令狐提出
data = [1,3,6,8,8,12,88,943] # 第一个等于target的索引位置 def binarySearch(nums,target): if not nums: return -1 start, end = 0, len(nums)-1 while start + 1 < end: mid = start + (end-start)//2 if nums[mid] == target: end = mid elif nums[mid] < target: start = mid else: end = mid if nums[start] == target: return start if nums[end] == target: return end binarySearch(data, 8)
data = [1,3,6,8,8,12,88,943] # 最后一个等于target的索引位置 def binarySearch(nums,target): if not nums: return -1 start, end = 0, len(nums)-1 while start + 1 < end: mid = start + (end-start)//2 if nums[mid] == target: start = mid elif nums[mid] < target: start = mid else: end = mid if nums[start] == target: return start if nums[end] == target: return end binarySearch(data, 8)
时刻记着自己要成为什么样的人!