Search Insert Position

塵埃092發表於2014-08-11
class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        int begin, mid, end;
        begin = 0; end = n-1;
        while( begin < end )
        {
            mid = (end+begin) / 2;
            if( target == A[mid] )
                return mid;
            else if( target > A[mid] )
            {
                begin = mid+1;    
            }
            else if( target < A[mid] )
            {
                end = mid-1;
            }
        }
        if( target <= A[begin] )
            return begin;
        else
            return begin+1;
    }
};

相關文章