32 lines
849 B
Python
32 lines
849 B
Python
"""
|
|
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
|