Day10-Search Insert Position(easy)
问题描述:
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.
从一个有序列表中找到target的值,返回其下标,如果不存在这个值就返回插入这个值的下标位置。
Example:
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 4:
Input: [1,3,5,6], 0
Output: 0
解法一O(N):
暴力破解,从头开始遍历数组。遇到不用说了就直接返回下标,如果没遇到就返回刚好大于这个值的下标位置。
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
#暴力破解
i = 0
while i < len(nums):
if nums[i] >= target:
return i
else:
i += 1
return i
解法二O(logN):
二分搜索法
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
#二分搜索法
start,end = 0,len(nums) - 1
while start <= end:
mid = (start + end) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
end = mid - 1
else:
start = mid + 1
return start