Search Insert Position

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

Solution:

  1. public class Solution {
  2. public int searchInsert(int[] nums, int target) {
  3. return search(nums, target, 0, nums.length - 1);
  4. }
  5. int search(int[] nums, int target, int lo, int hi) {
  6. if (lo > hi) {
  7. return lo;
  8. }
  9. int mid = lo + (hi - lo) / 2;
  10. if (nums[mid] == target) {
  11. return mid;
  12. }
  13. if (target < nums[mid]) {
  14. return search(nums, target, lo, mid - 1);
  15. } else {
  16. return search(nums, target, mid + 1, hi);
  17. }
  18. }
  19. }