题目截图
思路:题目要就时间复杂度为,不能使用暴力求解,该要求是典型了二分法查找,只不过最后返回的不是True和False。而是数组索引。
方法:二分法
直接用二分法即可,无需任何创造,稍微修改一下返回值。
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
n = len(nums)
first = 0
last = n-1
while first <= last:
mid = (first + last) // 2
if target == nums[mid]:
return mid
elif target > nums[mid]:
first = mid + 1
else:
last = mid - 1
return first
if __name__ == "__main__":
a = Solution()
alist = [1, 3, 5, 6]
a_target = 2
print(a.searchInsert(alist,a_target))