leetcode 35. Search Insert Position 搜尋插入位置 python 簡單而高效的方法、二分查詢

NO IMAGE
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# Approach #1
# if target in nums:
#     return nums.index(target)
# else:
#     for index,num in enumerate(nums):
#         if target < nums[0]:
#             return 0
#         if target > nums[-1]:
#             return len(nums)
#         if num < target and nums[index 1] > target:
#             return index 1
# Approach #2   
left , right = 0 , len(nums) - 1
if target < nums[left]:
return 0
if target > nums[right]:
return len(nums)
while right - 1 > left :
mid = ( left   right ) // 2
if  target < nums[mid]:
right = mid
elif nums[mid] < target:
left = mid
if nums[mid] == target:
return mid
return left   1