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
int searchInsert(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
}
}
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)
Approach 2: Linear Search
int searchInsert(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
if (nums[i] >= target) {
return i;
}
}
return nums.size();
}
Explanation
- Iterate through the array using a for loop.
- If the current element is greater than or equal to the target, return the current index.
- If the loop completes without finding a suitable position, return the length of the array.
Analysis
- Time Complexity:
O(n)
- Space Complexity:
O(1)
Last updated on