① int left_bound(int[] nums, int target) { if (nums.length == 0) return -1; int left = 0; int right = nums.length; // 注意
while (left < right) { // 注意 int mid = (left + right) / 2; if (nums[mid] == target) { right = mid; } else if (nums[mid] < target) { left = mid + 1; } else if (nums[mid] > target) { right = mid; // 注意 } } return left; } ② int left_bound(int[] nums, int target) { if (nums.length == 0) return -1; int left = 0; int right = nums.length - 1; // 注意
while (left <= right) { // 注意 int mid = (left + right) / 2; if (nums[mid] == target) { right = mid - 1; } else if (nums[mid] < target) { left = mid + 1; } else if (nums[mid] > target) { right = mid - 1; // 注意 } } // 最后要检查 left 越界的情况 if (left >= nums.length || nums[left] != target) return -1; return left; }
int right = nums.length 表示 [left, right) 范围内的数据都要考虑,而 right 对应的数据不做考虑,所以当 nums[mid] > target 时, right = mid 即可。而当 nums[mid] == target 时,因为目标是拿到做边界,所以需要让 right = mid 来压缩区间范围,向左靠拢