题目要求:
要求在给定的有序数组中查找目标值,如果找到target则返回索引, 如果没有则返回它应该插入的位置的索引。限定条件,时间复杂度为O(log n)。
Problem Description:
Given a sorted array of distinct integers 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 must write an algorithm with O(log n)
runtime complexity.
思路:
这道题是别致一点的二分查找题,且二分查找的时间复杂度符合这道题的限制条件。
首先,将数组中间位置的值和target比较,如果两者相等则查找成功;否则利用中间位置将数组分成前、后两个子数组,如果中间位置的值大于target,则进一步查找前一子数组,否则进一步查找后一子数组。
重复以上过程,直到找到target,使查找成功,或直到子数组不存在为止,此时查找不成功。
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
left = 0
right = length - 1
if nums is None or target < nums[0]:
return 0
elif target > nums[-1]:
return length
else:
while left <= right:
mid = int((left + right)/2)
if target < nums[mid]:
right = mid - 1
elif target > nums[mid]:
left = mid + 1
else:
return mid
return left
结果如下:
二分查找:
二分查找又称折半查找,它是一种效率较高的查找方法。二分查找要求:线性表是有序表,即表中结点按关键字有序,并且要用向量作为表的存储结构。不妨设有序表是递增有序的。
本质上是一个不断缩小搜索空间的过程。