Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # target_index = 0 # for i in range(len(nums)): # if (i == 0 and nums[0] >= target): # return 0 # elif ( target > nums[i-1] and target <= nums[i]): # return i # elif (target > nums[len(nums)-1]): # return len(nums) minGuess = 0 maxGuess = len(nums)-1 while(maxGuess >= minGuess): guess = (minGuess + maxGuess)/2 if(nums[guess] == target): return guess elif(nums[guess] < target): minGuess = guess + 1 else: maxGuess = guess - 1 return minGuess
由于提供给的数组是一个有序数组,是可以使用二分查找来做的