1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| /** * 这道题要用二分法找到左边的开始位置,以及右边的结束位置 * 同时需要考虑,target不在数组中 * <p> * 情况一:target 在数组范围的右边或者左边,例如数组{3, 4, 5},target为2或者数组{3, 4, 5},target为6,此时应该返回{-1, -1} * 情况二:target 在数组范围中,且数组中不存在target,例如数组{3,6,7},target为5,此时应该返回{-1, -1} * 情况三:target 在数组范围中,且数组中存在target,例如数组{3,6,7},target为6,此时应该返回{1, 1} */ public int[] searchRange(int[] nums, int target) { if (nums.length == 0) { return new int[]{-1, -1}; } int rithtIndex = rithtIndex(nums, target); int leftIndex = leftIndex(nums, target); if (rithtIndex == -2 || leftIndex == -2) { return new int[]{-1, -1}; } if (rithtIndex - leftIndex > 1) return new int[]{leftIndex + 1, rithtIndex - 1}; return new int[]{-1, -1}; }
public int rithtIndex(int[] nums, int target) { int l = 0; int r = nums.length - 1; int rithtIndex = -2; while (l <= r) { int mid = l + (r - l) / 2; if (nums[mid] > target) {//一直缩小右边界 r = mid - 1; } else { l = mid + 1; rithtIndex = l; } } return rithtIndex; }
public int leftIndex(int[] nums, int target) { int l = 0; int r = nums.length - 1; int leftIndex = -2; while (l <= r) { int mid = l + (r - l) / 2; if (nums[mid] < target) {//一直缩小右边界 l = mid + 1; } else { r = mid - 1; leftIndex = r; } } return leftIndex; }
|