Easy
,Array
,Binary Search
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.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Constraints:
nums.length
<= 104nums[i]
<= 104nums
contains distinct values sorted in ascending order.target
<= 104
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
L, R = 0, len(nums) - 1
while L <= R:
M = (L + R) // 2
if nums[M] == target:
return M
if target < nums[M]:
R = M - 1
else:
L = M + 1
return R + 1
Yen-Chi ChenMon, Feb 20, 2023
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return bisect_left(nums, target)
Yen-Chi ChenMon, Feb 20, 2023
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums)
while l < r:
mid = l + (r - l) // 2
if nums[mid] >= target:
r = mid
else:
l = mid + 1
return l
Ron ChenWed, Feb 22, 2023
function searchInsert(nums, target) {
let max = nums.length - 1;
let min = 0;
while (min <= max) {
const position = ~~((max + min) / 2);
if (nums[position] === target) return position;
if (nums[position] > target) {
max = position - 1;
} else {
min = position + 1;
}
}
return max + 1;
}
MasrgoatMon, Feb 20, 2023