一、题目
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.
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 1:
Input: [1,3,5,6], 0 Output: 0
二、解题思路
首先此题要分两种大情况:
1、target in nums: 此种情况比较简单,遍历nums,找到target,返回索引即可;
2、target not in nums:此种情况下,要分为三小种情况:
(1)target比nums[0]小,返回0
(2)target比num[len(nums)]大,返回len(nums)
(3)target在nums[0]~nums[len(nums)-1]之间的话,就要比较用target与相邻的nums[i]和nums[i+1]比较
三、代码
#coding:utf-8 import time def searchInsert1(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if target in nums: for i in range(len(nums)): if target == nums[i]: print(i) return i else: if target < nums[0]: print(0) return 0 if target > nums[len(nums)-1]: print(len(nums)) return len(nums) for j in range(len(nums)): if target > nums[j] and target < nums[j+1]: print(j+1) return j+1 def searchInsert2(nums, target): first = 0 last = len(nums) - 1 while first < last: mid = (first + last + 1) // 2 if nums[mid] == target: print(mid) return mid if nums[mid] < target: first = mid + 1 else: last = mid - 1 if nums[last] < target: print(last+1) return last + 1 if target <= nums[last]: print(last) return last if target < nums[first]: print(first) return first print(first+1) return first + 1 def searchInsert3(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = len(nums) - 1 while low <= high: mid = low + (high - low) / 2 if nums[mid] < target: low = mid + 1 elif nums[mid] > target: high = mid - 1 else: return mid return low if __name__ == '__main__': a = [1,2,3,5,6,7,8] b = 4 starttime = time.clock() searchInsert1(a,b) endtime = time.clock() print("the first run time is: %s ",(endtime - starttime)) print("_______________") starttime2 = time.clock() searchInsert2(a, b) endtime2 = time.clock() print("the second run time is: %s",(endtime2 - starttime2)) print("_______________") starttime3 = time.clock() #searchInsert3(a, b) endtime3 = time.clock() print("the third run time is: %s", (endtime3 - starttime3))
考虑此问题,我并没有将数据结构考虑进来,所以并不完美,网上清一色的使用的是二分查找,把别人的代码贴出来,供学习,二分查找的速度比我写的快很多。