Monday, June 23, 2014

Leecode Search Insert Position

O(logn) Binary Search

 public int searchInsert(int[] A, int target) {
        if (A == null) return 0;
        return searchInsert(A,target, 0, A.length-1);
    }
    private int searchInsert(int[] A, int target, int start, int end) {
        int mid = (start+end)/2;
        if (target == A[mid]) {
            return mid;
        } else if (target < A[mid]) {
            return start < mid ? searchInsert(A, target, start, mid-1) : start;
        } else {
            return end > mid ? searchInsert(A, target, mid+1, end) : (end + 1);
        }
       
    }

No comments:

Post a Comment