1. 题目:
704.二分查找(Easy)
1代码:
class Solution:
def search(self, nums: List[int], target: int) -> int:
left , right = 0 ,len(nums)-1
while left <= right :
mid = (left+right)//2 # // 取整除,向下整除,9//2 = 4
if nums[mid] == target: # 先判断是否等,若等即不用返回
return mid
elif nums[mid] < target: # 若Mid<target ,则应该在[mid+1,right]搜索。left = mid+1
left = mid + 1
else: #若Mid>target ,则应该[left,mid-1]搜索,right mid-1
right = mid -1
#搜索不到返回-1
return -1