From cb08f3ce4e0f7003a5ae96c163cade388b29be73 Mon Sep 17 00:00:00 2001 From: ktkovachev <143198904+ktkovachev@users.noreply.github.com> Date: Mon, 8 Apr 2024 16:22:30 +0100 Subject: [PATCH] Solve 35. Search Insert Position --- python/35_search_insert_position.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 python/35_search_insert_position.py diff --git a/python/35_search_insert_position.py b/python/35_search_insert_position.py new file mode 100644 index 0000000..e4a448d --- /dev/null +++ b/python/35_search_insert_position.py @@ -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