题目

image.png

思路

  • 就是二分法的左边界和右边界而已

    代码

    1. //1.遍历版本1
    2. public int[] searchRange(int[] nums, int target) {
    3. int[] res = new int[]{-1, -1};
    4. if (nums.length == 0) return res;
    5. int i = 0, j = nums.length, index = -1;
    6. //左边界
    7. while (i < j) {
    8. index = (i + j) / 2;
    9. if (target == nums[index]) {
    10. i = index + 1;
    11. res[1] = index;
    12. } else if (target > nums[index]) {
    13. i = index + 1;
    14. } else if (target < nums[index]) {
    15. j = index;
    16. }
    17. }
    18. i = 0; j = nums.length;
    19. //右边界
    20. while (i < j) {
    21. index = (i + j) / 2;
    22. if (target == nums[index]) {
    23. j = index;
    24. res[0] = index;
    25. } else if (target > nums[index]) {
    26. i = index + 1;
    27. } else if (target < nums[index]) {
    28. j = index;
    29. }
    30. }
    31. return res;
    32. }
    33. //2.遍历版本2
    34. public int[] searchRange(int[] nums, int target) {
    35. int[] res = new int[]{-1, -1};
    36. if (nums.length == 0) return res;
    37. int i = 0, j = nums.length - 1, index = -1;
    38. //左边界
    39. while (i <= j) {
    40. index = (i + j) / 2;
    41. if (target == nums[index]) {
    42. i = index + 1;
    43. res[1] = index;
    44. } else if (target > nums[index]) {
    45. i = index + 1;
    46. } else if (target < nums[index]) {
    47. j = index - 1;
    48. }
    49. }
    50. i = 0; j = nums.length - 1;
    51. //右边界
    52. while (i <= j) {
    53. index = (i + j) / 2;
    54. if (target == nums[index]) {
    55. j = index - 1;
    56. res[0] = index;
    57. } else if (target > nums[index]) {
    58. i = index + 1;
    59. } else if (target < nums[index]) {
    60. j = index - 1;
    61. }
    62. }
    63. return res;
    64. }
    65. //3.递归版本
    66. public int[] searchRange(int[] nums, int target) {
    67. int leftIdx = binarySearch(nums, target, true);
    68. int rightIdx = binarySearch(nums, target, false) - 1;
    69. if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) {
    70. return new int[]{leftIdx, rightIdx};
    71. }
    72. return new int[]{-1, -1};
    73. }
    74. public int binarySearch(int[] nums, int target, boolean lower) {
    75. int left = 0, right = nums.length - 1, ans = nums.length;
    76. while (left <= right) {
    77. int mid = (left + right) / 2;
    78. if (nums[mid] > target || (lower && nums[mid] >= target)) {
    79. right = mid - 1;
    80. ans = mid;
    81. } else {
    82. left = mid + 1;
    83. }
    84. }
    85. return ans;
    86. }

    在排序数组中查找元素的第一个和最后一个位置