LeetCode Search Insert Position

二分插入

def searchInsert(self, nums, target):
        l, r, i = 0, len(nums)-1, 0
        while l<r:
            i = (l+r)/2
            if nums[i]<target:
                if l==i:
                    i += 1
                l = i
            elif nums[i]>target:
                r = i
            else:
                return i
        if nums[i]<target:
            return i+1
        return i

 

关注插入点 Most Voted Solution

public int searchInsert(int[] A, int target) {
        int low = 0, high = A.length-1;
        while(low<=high){
            int mid = (low+high)/2;
            if(A[mid] == target) return mid;
            else if(A[mid] > target) high = mid-1;
            else low = mid+1;
        }
        return low;
    }