class Solution {
public int[] searchRange(int[] nums, int target) {
return recur(0, nums.length - 1, nums, target);
}
public int[] recur(int left, int right, int[] nums, int target) {
while (left <= right) {
int mid = (left + right) >> 1;
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
if (nums[left] != target) {
// 因为left不是target需要向右移动
因为nums{left}不等于target,需要向右移动去寻找,同理调用递归
left = recur(left + 1, mid, nums, target)[0];
}
if (nums[right] != target) {
right = recur(mid, right - 1, nums, target)[1];
}
return new int[] {left, right};
}
}
return new int[] {-1, -1};
}
}
思路:只要nums【mid】>=target的时候,说明还需要移动右端点,直到nums【mid】<target,然后左端点移动,导致left>right是循环结束,结果值就是上一次循环的结果。