Given a sorted array 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 may assume no duplicates in the array.
Here are few examples.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
O(n) complexity solution:
public class Solution {
public int searchInsert(int[] nums, int target) {
int i = 0;
for (i = 0; i < nums.length; i++) {
if (nums[i] >= target) return i;
}
return i;
}
}
O(log n) complexity solution:
public int searchInsert(int[] nums, int target) {
return search(nums, target, 0, nums.length - 1);
}
public int search(int[] nums, int target, int start, int end) {
if (start == end && nums[start] > target) return start;
else if (start == end && nums[start] < target) return start + 1;
if (nums[(start + end)/2] == target) return (start + end)/2;
if (nums[(start + end)/2] < target) return search(nums, target, (start + end)/2 + 1, end);
else return search(nums, target, start, (start + end)/2);
}