Wednesday, March 4, 2015

35. Search Insert Position Leetcode Java

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.Brute force
From start to end search the insertion position. Time Complexity: O(n). Code was not provided.
2. Binary Search
Regular binary search. If there is an element with same value, return that position. After the search was done the l pointer will be the insertion point.
Time complexity: O(logn)
 public int searchInsert(int[] A, int target) {  
    if(A==null || A.length==0) return 0;  
    int l=0;  
    int r=A.length-1;  
    while(l<=r){  
      int m=(r-l)/2+l;  
      if(A[m]==target) return m;  
      else if(A[m]<target) l=m+1;  
      else r=m-1;  
    }  
    return l;  
   }  

No comments:

Post a Comment