2014年4月12日 星期六

[LeetCode] Search Insert Position

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
Solution: O(logn)
public class Solution {
    public int searchInsert(int[] A, int target) {
        return  getIndex(A,0,A.length-1,target);
   }
   public int getIndex(int[] A, int start, int end, int target){
       if(A.length == 0 || target < A[start])
           return start;
       if(target > A[end]) 
           return end+1;
           
       if(start == end){
           if(target == A[start])
               return start;
           else if(target > A[start])
               return start+1;
           else
               return end -1;
       }
       int mindex = (start+end)/2;
       int mvalue = A[mindex];
       if(mvalue == target)
           return mindex;
       else if(mvalue > target)
           return getIndex(A, start, mindex-1, target);
       else 
           return getIndex(A, mindex+1, end, target);
   }
}

沒有留言:

張貼留言