|
| 1 | +public class FirstAndLastOccurrencesOfANumber { |
| 2 | + public int[] firstAndLastOccurrencesOfANumber(int[] nums, int target) { |
| 3 | + int lowerBound = lowerBoundBinarySearch(nums, target); |
| 4 | + int upperBound = upperBoundBinarySearch(nums, target); |
| 5 | + return new int[]{lowerBound, upperBound}; |
| 6 | + } |
| 7 | + |
| 8 | + private int lowerBoundBinarySearch(int[] nums, int target) { |
| 9 | + if (nums == null || nums.length == 0) return -1; |
| 10 | + int left = 0; |
| 11 | + int right = nums.length - 1; |
| 12 | + while (left < right) { |
| 13 | + int mid = (left + right) / 2; |
| 14 | + if (nums[mid] > target) { |
| 15 | + right = mid - 1; |
| 16 | + } else if (nums[mid] < target) { |
| 17 | + left = mid + 1; |
| 18 | + } else { |
| 19 | + right = mid; |
| 20 | + } |
| 21 | + } |
| 22 | + return nums[left] == target ? left : -1; |
| 23 | + } |
| 24 | + |
| 25 | + private int upperBoundBinarySearch(int[] nums, int target) { |
| 26 | + if (nums == null || nums.length == 0) return -1; |
| 27 | + int left = 0; |
| 28 | + int right = nums.length - 1; |
| 29 | + while (left < right) { |
| 30 | + // In upper-bound binary search, bias the midpoint to the right. |
| 31 | + int mid = (left + right) / 2 + 1; |
| 32 | + if (nums[mid] > target) { |
| 33 | + right = mid - 1; |
| 34 | + } else if (nums[mid] < target) { |
| 35 | + left = mid + 1; |
| 36 | + } else { |
| 37 | + left = mid; |
| 38 | + } |
| 39 | + } |
| 40 | + // If the target doesn't exist in the array, then it's possible that |
| 41 | + // 'left = mid + 1' places the left pointer outside the array when |
| 42 | + // 'mid == n - 1'. So, we use the right pointer in the return |
| 43 | + // statement instead. |
| 44 | + return nums[right] == target ? right : -1; |
| 45 | + } |
| 46 | +} |
0 commit comments