class binary_search(object):
def __init__(self, nums, target):
self.nums = nums
self.target = target
def binary_search_template_1(self):
if len(self.nums) == 0:
return -1
l, r = 0, len(self.nums) - 1
while (l <= r):
mid = (l + r) // 2
if self.nums[mid] == self.target:
return mid
elif self.nums[mid] < self.target:
l = mid + 1
else:
r = mid - 1
return -1
def binary_search_template_2(self):
if len(self.nums) == 0:
return -1
l, r = 0, len(self.nums)
while l < r:
mid = (l + r) // 2
if self.nums[mid] == self.target:
return mid
elif self.nums[mid] < self.target:
l = mid + 1
else:
r = mid
if l != len(self.nums) and nums[l] == self.target:
return l
return -1
def binary_search_template_3(self):
if len(self.nums) == 0:
return -1
l, r = 0, len(self.nums) - 1
while l + 1 < r:
mid = (l + r) // 2
if self.nums[mid] == self.target:
return mid
elif self.nums[mid] < self.target:
l = mid
else:
r = mid
if self.nums[l] == self.target:
return l
if self.nums[r] == self.target:
return r
return -1
标签:二分,binary,search,target,nums,PYTHON,self,模板
From: https://www.cnblogs.com/cloucodeforfun/p/18674319