class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left,right=0,len(nums)-1
while left<=right:
# 获得中点:中点不管哪种区间取法都是一样的
# 写法1是通常采用的,因为这避免直接相加导致的数值溢出
mid = left + (right - left) // 2
# mid = (left + right) // 2 #写法2
num=nums[mid]
if num==target:
return mid
elif num > target:
right = mid - 1
else:
left = mid + 1
return -1
704. 二分查找
最新推荐文章于 2024-11-14 08:53:59 发布