思路:就是二分查找,只是查找一个数的范围,思路和二分查找相似,只是在mid查找到此数后,利用right-- 或 left++ 寻找该数的右边界和左边界。
Java代码如下:
public int[] searchRange(int[] nums, int target) { int[] result = {-1, -1}; int left = 0, right = nums.length - 1; while (left <= right) { if (nums[left] == target && nums[right] == target) { //when find both left index and right index, return. result[0] = left; result[1] = right; return result; } int mid = (left + right)/2; if (nums[mid] == target) { if (nums[right] != target) { // this if and else is very important! right--; } else { left++; } } else if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } return result; }