二分法
1 题目
35. 搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
2 解法
使用二分搜索算法,注意边界条件
class Solution(object):
def searchInsert(self, nums, target):
Found = False
head = 0
tail = len(nums)
if(tail - head == 1):
if(nums[0] >= target):
return 0
else:
return 1
else:
if(nums[tail - 1]) < target:
return len(nums)
elif(nums[tail - 1]) == target:
return len(nums) - 1
elif(nums[head] >= target):
return head
else:
while Found != True and (tail - head) > 1 :
if(nums[(head + tail)/2] == target):
Found = True
elif(nums[(head + tail)/2] > target):
tail = (head + tail)/2
elif(nums[(head + tail)/2] < target):
head = (head + tail)/2
if(tail - head > 1):
return (head + tail)/2
else:
return tail