Problem Statement
Pattern: Binary Search
Solution
static int search(int[] nums, int target, boolean findLeft) {
int start = 0, end = nums.length - 1, mid ans = -1;
// find left-most occurrence
while (start <= end) {
mid = start + (end - start) / 2;
if (nums[mid] < target) start = mid + 1;
else if (nums[mid] > target) end = mid - 1;
// if target found
else {
ans = mid; // update ans
if (findLeft) end = mid - 1; // keep searching left of mid
else start = mid + 1; // keep searching right of mid
}
}
return ans;
}
public static int[] searchRange(int[] nums, int target) {
int[] ans = {-1, -1};
ans[0] = search(nums, target, true);
ans[1] = search (nums, target, false);
return ans;
}