1 """ 2 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. 3 You may assume no duplicates in the array. 4 Example 1: 5 Input: [1,3,5,6], 5 6 Output: 2 7 Example 2: 8 Input: [1,3,5,6], 2 9 Output: 1 10 Example 3: 11 Input: [1,3,5,6], 7 12 Output: 4 13 Example 4: 14 Input: [1,3,5,6], 0 15 Output: 0 16 """ 17 """ 18 本题提供两种解法,第一种是遍历有序的数组 19 遇到大于等于 target的位置插入 20 """ 21 class Solution1: 22 def searchInsert(self, nums, target): 23 if nums[-1] < target: #边界条件 24 return len(nums) 25 if nums[0] > target: 26 return 0 27 for i in range(len(nums)): 28 if nums[i] >= target: #!!!关键点 29 return i 30 31 """ 32 二分法 33 对于二分法的 left right mid之间的转换 34 目前的思路是 更换测试用例 来不断修正如何转换 35 传送门:https://www.jianshu.com/p/46b8d8a55888 36 """ 37 class Solution2: 38 def searchInsert(self, nums, target): 39 if not nums: 40 return 0 41 left = 0 42 right = len(nums) 43 while left < right: 44 mid = (left+right)//2 45 if nums[mid] >= target: 46 right = mid 47 else: 48 left = mid + 1 49 return left