力扣35

张碧晨 / 2024-08-28 / 原文

1.Java的二分查找

public int searchInsert(int[] nums, int target) {
        int i = 0, j = nums.length - 1;
        while (i <= j) {
            int m = (i + j) >>> 1;
            if (target < nums[m]) {
                j = m - 1;
            } else if (target > nums[m]) {
                i = m + 1;
            } else {
                return m;
            }
        }
        return i;
}

 2.二分查找的leftmost版本

public int searchInsert(int[] nums, int target) {
        int i = 0, j = nums.length - 1;
        int flag = -1;
        while (i <= j) {
            int m = (i + j) >>> 1;
            if (target <= nums[m]) {
                j = m - 1;
            } else {
                i = m + 1;
            }
        }
        return i;
}