Search Insert Position
Description
- 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.
Constraints
1 <= n <= 10^4
-10^4 <= nums[i] <= 10^4
nums
contains distinct values sorted in ascending order.-10^4 <= target <= 10^4
Test Cases
-
Input:
nums = [1, 3, 5, 6], target = 5
Output:2
-
Input:
nums = [1, 3, 5, 6], target = 2
Output:1
-
Input:
nums = [1, 3, 5, 6], target = 7
Output:4
Code
Approach 1: Binary Search
Explanation
- Initialize
left
to0
andright
tonums.size() - 1
. - Use a while loop to perform binary search.
- Calculate the middle index
mid
usingleft + (right - left) / 2
. - If
nums[mid]
is equal totarget
, returnmid
. - If
nums[mid]
is less thantarget
, updateleft
tomid + 1
. - Otherwise, update
right
tomid - 1
. - If the loop exits without finding the target, return
left
.
Analysis
- Time Complexity:
O(log n)
- Space Complexity:
O(1)