34. 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

---

BST

---

public class Solution {
    public int searchInsert(int[] A, int target) {
        
        return helper(A, target, 0, A.length-1);
        
    }
      
    
    private int helper(int[] A, int target, int l, int r){
        
        // not found
        if(l > r) return l;   
            
        // bst 
        int mid = l + (r-l) / 2;
      
        if(A[mid] == target){   
            // found
            return mid;
                    
        }else if(A[mid] > target){
            // search left
            return helper(A, target, l, mid-1);
            
        }else{
            // search right
            return helper(A, target, mid+1, r);        
        }
    }
}

 

posted @ 2013-09-04 09:48  LEDYC  阅读(155)  评论(0)    收藏  举报