题解 | #二分查找-II python解法#
二分查找-II
http://www.nowcoder.com/practice/4f470d1d3b734f8aaf2afb014185b395
首先判断数组为空或数组长度为一的情况,然后用start和end,middle进行二分查找,若middle处的值=target,需要继续向前寻找,最终会出现start=end-1的情况,判断首尾后,跳出循环
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 如果目标值存在返回下标,否则返回 -1 # @param nums int整型一维数组 # @param target int整型 # @return int整型 # class Solution: def search(self , nums , target ): # write code here length = len(nums) #数组的长度 if length == 0: #数组为空 return -1 elif length ==1: #数组长度为1 return -1 if nums[0] != target else 0 start = 0 #首 end = length-1 #尾 index = -1 #存储返回的索引 while (True): middle = int((start+end)/2) value = nums[middle] if value == target: #若middle处遇到target,则赋值给index,并继续向前查找 index = middle end = middle elif value>target: end = middle else: start = middle if start == end -1: # 当start=end-1的情况,判断首尾后,跳出循环 if nums[start] == target: index = start break if nums[end] == target: index = end break break return index