左侧边界
1 int left_bound(int[] nums, int target) { 2 int left = 0, right = nums.length - 1; 3 // 搜索区间为 [left, right] 4 while (left <= right) { 5 int mid = left + (right - left) / 2; 6 if (nums[mid] < target) { 7 // 搜索区间变为 [mid+1, right] 8 left = mid + 1; 9 } else if (nums[mid] > target) { 10 // 搜索区间变为 [left, mid-1] 11 right = mid - 1; 12 } else if (nums[mid] == target) { 13 // 收缩右侧边界 14 right = mid - 1; 15 } 16 } 17 // 检查出界情况 18 if (left >= nums.length || nums[left] != target) { 19 return -1; 20 } 21 return left; 22 }
右侧边界
1 int right_bound(int[] nums, int target) { 2 int left = 0, right = nums.length - 1; 3 while (left <= right) { 4 int mid = left + (right - left) / 2; 5 if (nums[mid] < target) { 6 left = mid + 1; 7 } else if (nums[mid] > target) { 8 right = mid - 1; 9 } else if (nums[mid] == target) { 10 // 这里改成收缩左侧边界即可 11 left = mid + 1; 12 } 13 } 14 // 这里改为检查 right 越界的情况,见下图 15 if (right < 0 || nums[right] != target) { 16 return -1; 17 } 18 return right; 19 }