Search Insert Position

二分,多设立一个返回条件变可以继承二分法

ublic class Solution {
    public int searchInsert(int[] A, int target) {
        
        int l = 0, r = A.length-1;
        while(l<=r){
            int m = (l+r)/2;
            if(A[m]==target) return m;
            if(m+1<A.length && A[m]< target && A[m+1]>target){
                    return m+1;
            }
            if(A[m]< target){
                l = m+1;
            }else
                r =m-1;
        }
        return l;
    }
}

参考 http://fisherlei.blogspot.com/2013/01/leetcode-search-insert-position.html

posted @ 2015-04-14 06:25  世界到处都是小星星  阅读(151)  评论(0编辑  收藏  举报