Solve 35. Search Insert Position

This commit is contained in:
ktkovachev 2024-04-08 16:22:30 +01:00 committed by GitHub
parent c7048b8b19
commit cb08f3ce4e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -0,0 +1,21 @@
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
lower = 0
upper = len(nums)-1
while True:
mid = (upper + lower) // 2
if nums[mid] == target:
return mid
elif mid == 0 and nums[mid] > target:
return mid
elif mid >= len(nums) - 1:
if nums[mid] < target:
return mid + 1
else:
return mid
elif nums[mid] > target and nums[mid-1] < target:
return mid
elif nums[mid] < target:
lower = mid + 1
else:
upper = mid - 1