题目描述
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5 输出: 2
代码:
1 def binarySearch(nums, target): 2 ''' 3 4 :param nums: 5 :param target: 6 :return: 7 ''' 8 left, right = 0, len(nums) - 1 9 while left <= right: 10 # (right+left)//2存在内存溢出的情况,故采用下面更优! 11 mid = left + (right - left) // 2 12 if nums[mid] == target: 13 return mid 14 elif nums[mid] < target: 15 left = mid + 1 16 else: 17 right = mid - 1 18 19 return left 20 21 22 print("----------测试binarySearch()---------") 23 nums = [1, 2, 4, 6, 8, 9] 24 index = binarySearch(nums, 2) 25 print("index=", index) 26 27 28 def binarySearch1(nums, target): 29 ''' 30 31 :param nums: 32 :param target: 33 :return: 34 ''' 35 left, right = 0, len(nums) - 1 36 while left < right: 37 mid = left + (right - left) // 2 38 if nums[mid] == target: 39 return mid 40 elif nums[mid] < target: 41 left = mid + 1 42 else: 43 right = mid 44 45 # 此时left==right 46 if target <= nums[left]: 47 return left 48 else: 49 return left + 1 50 51 52 print("----------测试binarySearch1()---------") 53 nums = [1, 3, 5, 6] 54 index = binarySearch1(nums, 7) 55 print("index=", index)
输出:
----------测试binarySearch()--------- index= 1 ----------测试binarySearch1()--------- index= 4
总结:在二分查找中,最重要的是边界条件判断。在方法二中,判断条件为Left<right;当跳出循环时,left=right,此时元素nums[left]并未加入判断。所以需要在后面再进一步判断targte是否和nums[left]相等,方法中采用的<=,满足则返回left,反之返回left+1