Leetcode::Search Insert Position

二分查找法

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int start = 0;
        int end = n - 1;
        while( start <= end )
        {
            int mid = ( start + end ) / 2;
            
            if( target ==  A[ mid ] )
                return mid;
            else if( target > A[ mid ] )
                start = mid + 1;
            else
                end = mid - 1;
                
            
        }
        
        return max( start, end );
    }
};

  

posted @ 2013-10-30 09:46  NinaGood  阅读(116)  评论(0)    收藏  举报