Coding · Medium · Pro
Find first and last position of a target in a sorted array
CodingBinary SearchSenior
Approach
- Run binary search twice: once for the leftmost index, once for the rightmost.
- For left bound: when
nums[mid] == target, record answer and movehi = mid - 1. - For right bound: when equal, move
lo = mid + 1.
Java Solution
Java
public class FirstLastPosition {
public static int[] searchRange(int[] nums, int target) {…