java刷题--34在排序数组中查找元素的第一个和最后一个位置
题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b305b24a922266c3fbe1b4e71d3446de.png)
代码
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[] {-1, -1};
res[0] = binarySearch(nums, target, true);
res[1] = binarySearch(nums, target, false);
return res;
}
public int binarySearch(int[] nums, int target, boolean leftOrRight) {
int res = -1;
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(target < nums[mid])
right = mid - 1;
else if(target > nums[mid])
left = mid + 1;
else {
res = mid;
if(leftOrRight)
right = mid - 1;
else
left = mid + 1;
}
}
return res;
}
}
结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/570207fac58b86bad286708b7d89d2a5.png)