# The Problem:

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

# Notes:

- Be careful about bounds, and do binary search.
- Attention to return low or high, also see in Sqrt(x)
- Mistake I made:
- if target equals to or less than first number, both return 0; but if target equals to last number return length-1, greater than last number should return length.

# Java Solution

public class Solution { public int searchInsert(int[] A, int target) { if(A==null || A.length==0) return 0; if(target <= A[0]) return 0; if(target > A[A.length-1]) return A.length; int low = 0; int high = A.length-1; while(low <= high){ int mid = (high+low)/2; if(A[mid]==target) return mid; if(A[mid] < target){ low = mid+1; } else{ high = mid-1; } } return low; } }

Advertisements