就是二分法的左边界和右边界而已
代码
//1.遍历版本1 public int[] searchRange(int[] nums, int target) { int[] res = new int[]{-1, -1}; if (nums.length == 0) return res; int i = 0, j = nums.length, index = -1; //左边界 while (i < j) { index = (i + j) / 2; if (target == nums[index]) { i = index + 1; res[1] = index; } else if (target > nums[index]) { i = index + 1; } else if (target < nums[index]) { j = index; } } i = 0; j = nums.length; //右边界 while (i < j) { index = (i + j) / 2; if (target == nums[index]) { j = index; res[0] = index; } else if (target > nums[index]) { i = index + 1; } else if (target < nums[index]) { j = index; } } return res; } //2.遍历版本2 public int[] searchRange(int[] nums, int target) { int[] res = new int[]{-1, -1}; if (nums.length == 0) return res; int i = 0, j = nums.length - 1, index = -1; //左边界 while (i <= j) { index = (i + j) / 2; if (target == nums[index]) { i = index + 1; res[1] = index; } else if (target > nums[index]) { i = index + 1; } else if (target < nums[index]) { j = index - 1; } } i = 0; j = nums.length - 1; //右边界 while (i <= j) { index = (i + j) / 2; if (target == nums[index]) { j = index - 1; res[0] = index; } else if (target > nums[index]) { i = index + 1; } else if (target < nums[index]) { j = index - 1; } } return res; } //3.递归版本 public int[] searchRange(int[] nums, int target) { int leftIdx = binarySearch(nums, target, true); int rightIdx = binarySearch(nums, target, false) - 1; if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) { return new int[]{leftIdx, rightIdx}; } return new int[]{-1, -1}; } public int binarySearch(int[] nums, int target, boolean lower) { int left = 0, right = nums.length - 1, ans = nums.length; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] > target || (lower && nums[mid] >= target)) { right = mid - 1; ans = mid; } else { left = mid + 1; } } return ans; }
在排序数组中查找元素的第一个和最后一个位置