leetcode-35-easy

Search Insert Position
思路一: 二分查找,然后处理没有找到的情况

public int searchInsert(int[] nums, int target) {
    int i = Arrays.binarySearch(nums, target);
    if (i >= 0) return i;

    for (int j = 0; j < nums.length; j++) {
        if (nums[j] > target) return j;
    }

    return nums.length;
}

思路二: 直接在二分查找里面实现,最后 low 的位置就是 target

private static int searchInsert(int[] a, int key) {
    int fromIndex = 0;
    int toIndex = a.length - 1;
    int low = fromIndex;
    int high = toIndex - 1;

    while (low <= high) {
        int mid = (low + high) >>> 1;
        int midVal = a[mid];

        if (midVal < key)
            low = mid + 1;
        else if (midVal > key)
            high = mid - 1;
        else
            return mid; // key found
    }
    return key <= a[low] ? low : low + 1;  // key not found.
}
posted @ 2022-10-10 18:03  iyiluo  阅读(9)  评论(0)    收藏  举报