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 54
| class Solution { public int[] searchRange(int[] nums, int target) { if (nums.length == 0) { return new int[]{-1, -1}; } int index = search(nums, target, 0, nums.length - 1); if (index == -1) { return new int[]{-1, -1}; } return lookAround(nums, index); }
public int search(int[] nums, int target, int begin, int end) { if (begin == end) { return nums[begin] == target ? begin : -1; } int middle = (begin + end) / 2; if (nums[middle] == target) { return middle; } else if (nums[middle] < target) { if (middle == end) { return search(nums, target, middle, end); } else { return search(nums, target, middle + 1, end); } } else { if (middle == begin) { return search(nums, target, begin, middle); } else { return search(nums, target, begin, middle - 1); } } }
public int[] lookAround(int[] nums, int index) { int left = index, right = index; for (int i = index; i >= 0; i--) { if (nums[i] == nums[index]) { left--; } } for (int i = index; i < nums.length; i++) { if (nums[i] == nums[index]) { right++; } } return new int[]{left + 1, right - 1}; } }
|