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.
Example 1:
Example 2:
Example 3:
Constraints:
Perform binary search on the input array for target value.
If element is found:
If element is not found:
Logic:
Implementation: Recurssion
public int searchInsert(int[] nums, int target) {
return search(nums, 0, nums.length - 1, target);
}
/**
* Perform binary search to check for target element and determine the insertion positions if missing.
*
*/
public int search(int[] nums, int start, int end, int target) {
int mid = start + (end - start) / 2;
// insertion position
if (start >= end) {
if (target > nums[mid]) {
return mid + 1;
} else if (target < nums[mid]) {
return mid;
}
}
if (nums[mid] == target) {
return mid;
}
if (target > nums[mid]) {
return search(nums, mid + 1, end, target);
}
if (target < nums[mid]) {
return search(nums, start, mid - 1, target);
}
return -1;
}
Implementation: whhile loop
public int searchInsert(int[] nums, int target) {
return search(nums, 0, nums.length - 1, target);
}
/**
* Binary search using loop.
*/
public int searchloop(int[] nums, int target) {
int start = 0, end = nums.length -1;
while(start < end) {
int mid = start + (end - start) / 2;
if(nums[mid] == target) {
return mid;
} else if(target < nums[mid]) {
end = mid - 1;
} else if(target > nums[mid]) {
start = mid + 1;
}
}
if(target <= nums[start]) {
return start;
} else {
return start + 1;
}
}