二分法

    1. class Solution:
    2. def searchInsert(self, nums: List[int], target: int) -> int:
    3. left, right = 0, len(nums)
    4. while left < right:
    5. mid = left + (right - left) // 2
    6. if nums[mid] < target:
    7. left = mid + 1
    8. else:
    9. right = mid
    10. return left
    11. if __name__ == '__main__':
    12. samples = [
    13. (1, ([1, 3, 5, 6], 2)),
    14. (2, ([1, 3, 5, 6], 5)),
    15. (4, ([1, 3, 5, 6], 7)),
    16. (0, ([1, 3, 5, 6], 0)),
    17. ]
    18. for v, val in samples:
    19. print(v, Solution().searchInsert(*val))