力扣35

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;
}

 

posted @ 2024-08-27 20:14  张碧晨  阅读(9)  评论(0)    收藏  举报