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^4numscontains 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
leftto0andrighttonums.size() - 1. - Use a while loop to perform binary search.
- Calculate the middle index
midusingleft + (right - left) / 2. - If
nums[mid]is equal totarget, returnmid. - If
nums[mid]is less thantarget, updatelefttomid + 1. - Otherwise, update
righttomid - 1. - If the loop exits without finding the target, return
left.
Analysis
- Time Complexity:
O(log n) - Space Complexity:
O(1)