1. 在排序数组中查找数字
统计一个数字在排序数组中出现的次数。
方法一:
def search(nums, target):
return helper(nums, target) - helper(nums, target - 1)
def helper(nums, target):
i = 0
j = len(nums) - 1
while i <= j:
m = (i + j) // 2
if nums[m] <= target:
i = m + 1
else:
j = m - 1
return i
方法二:
def search(nums, target):
def binary_search(nums, target, lower):
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] > target or (lower and nums[mid] >= target):
right = mid - 1
else:
left = mid + 1
return left
return binary_search(nums, target, False) - binary_search(nums, target - 1, True)
标签:search,target,helper,nums,Study,Algorithms,Plan,def,left
From: https://blog.csdn.net/qq_24058289/article/details/142136940