4/06/2014

Leetcode -- Search Insert Position

class Solution {  
 public:  
   int searchInsert(int A[], int n, int target) {  
     int start = 0, end = n - 1;  
     while(start < end) {  
       int middle = (start + end) / 2;  
       if(target > A[middle]) {  
         start = middle+1;  
       } else if(target == A[middle]) {  
         return middle;  
       } else {  
         end = middle - 1;  
       }  
     }  
     if(A[start] >= target) {  
       return start ;  
       } else {  
       return start + 1;  
     }  
   }  
 }; 

No comments: