思路:
1.使用一个辅助函数,用来查找出元素出现的位置
2.元素往前遍历,直到找到的元素不等于想查找的元素
3.元素往后遍历,直到找到的元素不等于想查找的元素。
4.然后把left和right放到数组中返回
5.辅助函数:用二分查找法。
代码:
class Solution {
public int[] searchRange(int[] nums, int target) {
int find = searchRangeHelp(nums, target);
if (find == -1) {
return new int[]{-1, -1};
}
int left = find - 1, right = find + 1;
while (left >= 0 && nums[left] == target) left--;
while (right < nums.length && nums[right] == target) right++;
return new int[]{left + 1, right - 1};
}
private int searchRangeHelp(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}