代码语言:javascript复制
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = (low high) // 2
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid 1
return None
my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 7))
print(binary_search(my_list, -1))
LeetCode面试题53: 统计一个数字在排序数组中出现的次数。 示例 1:
输入: nums = [5,7,7,8,8,10], target = 8 输出: 2 示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
求解方法:
代码语言:javascript复制class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: return 0
left, right = 0, len(nums)-1
while left 1 < right:
mid = (left right) >> 1
if nums[mid] < target:
left = mid
else:
right = mid
count, end = 0,len(nums)-1
if nums[left] == target:
while left <= end and nums[left] == target :
left = 1
count = 1
return count
elif nums[right] == target:
while right <= end and nums[right] == target:
right = 1
count = 1
return count
else: return 0
LeetCode34 在排序数组中查找元素的第一个和最后一个位置
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8 输出: [3,4] 示例 2:
输入: nums = [5,7,7,8,8,10], target = 6 输出: [-1,-1]
解答:
代码语言:javascript复制class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if not nums: return [-1, -1]
# 确定左边界
left, right = 0, len(nums)-1
while left 1 < right:
mid = (left right) >> 1
if nums[mid] >= target:
right = mid
else:
left = mid
if nums[left] == target: lbound = left
elif nums[right] == target: lbound = right
else: return [-1, -1]
# 确定右边界
left, right = 0, len(nums)-1
while left 1 < right:
mid = (left right) >> 1
if nums[mid] <= target:
left = mid
else:
right = mid
if nums[right] == target: rbound = right
elif nums[left] == target: rbound = left
else: return [-1,-1]
return [lbound, rbound]