finish 35

This commit is contained in:
sangge 2024-03-09 04:15:57 +08:00
parent fe4a2064e8
commit d0633f9292

31
leetcode/35.py Normal file
View File

@ -0,0 +1,31 @@
"""
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.
Constraints:
1 <= nums.length <= 10^4
-10^4 <= nums[i] <= 10^4
nums contains distinct values sorted in ascending order.
-10^4 <= target <= 10^4
"""
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
low = 0
high = len(nums) - 1
while low <= high: # Changed the condition to low <= high
mid = (high + low) // 2
if target == nums[mid]:
return mid
elif target < nums[mid]:
high = mid - 1
else:
low = mid + 1
return low