|
1 | 1 | class Solution { |
2 | 2 | public int[] searchRange(int[] nums, int target) { |
3 | | - if (nums == null || nums.length == 0) { |
4 | | - return new int[] { -1, -1 }; |
5 | | - } |
6 | | - |
7 | | - int[] result = new int[2]; |
8 | | - result[0] = binarySearchHelperLow(nums, target); |
9 | | - result[1] = binarySearchHelperHigh(nums, target); |
10 | | - |
11 | | - return result; |
12 | | - } |
13 | | - |
14 | | - private int binarySearchHelperLow(int[] nums, int target) { |
15 | | - int low = 0, high = nums.length - 1; |
16 | | - |
17 | | - int idx = -1; |
18 | | - |
19 | | - while (low <= high) { |
20 | | - int mid = low + (high - low) / 2; |
21 | | - |
22 | | - if (nums[mid] == target) { |
23 | | - idx = mid; |
24 | | - } |
| 3 | + int firstIdx = binarySearch(nums, target, false); |
| 4 | + int secondIdx = binarySearch(nums, target, true); |
25 | 5 |
|
26 | | - if (nums[mid] >= target) { |
27 | | - high = mid - 1; |
28 | | - } else { |
29 | | - low = mid + 1; |
30 | | - } |
| 6 | + if (firstIdx == -1 || secondIdx == -1) { |
| 7 | + return new int[] { -1, -1 }; |
31 | 8 | } |
32 | 9 |
|
33 | | - return idx; |
| 10 | + return new int[] { firstIdx, secondIdx }; |
34 | 11 | } |
35 | 12 |
|
36 | | - private int binarySearchHelperHigh(int[] nums, int target) { |
| 13 | + private int binarySearch(int[] nums, int target, boolean moveRight) { |
37 | 14 | int low = 0, high = nums.length - 1; |
38 | | - |
39 | | - int idx = -1; |
| 15 | + int candidate = -1; |
40 | 16 |
|
41 | 17 | while (low <= high) { |
42 | 18 | int mid = low + (high - low) / 2; |
43 | 19 |
|
44 | 20 | if (nums[mid] == target) { |
45 | | - idx = mid; |
| 21 | + candidate = mid; |
46 | 22 | } |
47 | 23 |
|
48 | | - if (nums[mid] <= target) { |
49 | | - low = mid + 1; |
| 24 | + if (moveRight) { |
| 25 | + if (nums[mid] <= target) { |
| 26 | + low = mid + 1; |
| 27 | + } else { |
| 28 | + high = mid - 1; |
| 29 | + } |
50 | 30 | } else { |
51 | | - high = mid - 1; |
| 31 | + if (nums[mid] >= target) { |
| 32 | + high = mid - 1; |
| 33 | + } else { |
| 34 | + low = mid + 1; |
| 35 | + } |
52 | 36 | } |
53 | 37 | } |
54 | 38 |
|
55 | | - return idx; |
| 39 | + return candidate; |
56 | 40 | } |
57 | 41 | } |
0 commit comments