1 class Solution(object): 2 def search(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: int 7 """ 8 ## 暴力循环法 9 # for i in range(len(nums)): 10 # if target==nums[i]: 11 # return i 12 # if nums[i]>target or i==len(nums)-1: 13 # return -1 14 15 ## 二分查找法 16 ## 注意划分边界和终止条件,最好的方法就是实例,然后总结 17 left = 0 18 right = len(nums)-1 19 20 while(1): 21 mid = (left+right) // 2 22 if left==right and nums[left]!=target: 23 return -1 24 if target==nums[mid]: 25 return mid 26 elif target<nums[mid]: 27 right = mid 28 elif target>nums[mid]: 29 left = mid + 1
解题思路
1.暴力循环法,可以通过,但是耗时长
2.二分查找法
(1)确定初始左右边界
(2)注意二分时[left, right]都是闭区间(个人选择)
(3)实例推算,确定终止条件
标签:二分,right,target,nums,704,mid,力扣,left From: https://www.cnblogs.com/shi-yi/p/17251040.html