Search Insert Position
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.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Solution:
class Solution(object):
“”“
如果中间元素等于目标值,则直接返回中间位置;
如果中间元素小于目标值,则目标值应该在右半部分,更新left指针;
如果中间元素大于目标值,则目标值应该在左半部分,更新right指针。
最终如果找不到目标值,则返回左边界位置,表示目标值应该插入的位置。
”“”
def searchInsert(self, nums, target):
# 使用两个指针left和right表示数组的左右边界,然后在循环中使用二分查找算法进行查找
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
# 在 Python 中,两个斜杠(//)表示整数除法,它会将结果向下取整为最接近的整数
人生便是艺术。