Problem: 34. 在排序数组中查找元素的第一个和最后一个位置
思路
找左边界和右边界,二分法,总共分三种情况
- target本身超出数组范围,return{-1,-1}
- target在数组范围中,但是数组中不含target元素,return{-1,-1}
- 正确返回
解题方法
二分法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0PvPsXmz-1679042639299)(https://pic.leetcode.cn/1678983878-uEWvzA-%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230317002404.jpg)]
复杂度
- 时间复杂度:
O ( log n ) O(\log n) O(logn)
- 空间复杂度:
O ( 1 ) O(1) O(1)
Code
class Solution {
/**
分三种情况:
1. target本身超出数组范围,return{-1,-1}
2. target在数组范围中,但是数组中不含target元素,return{-1,-1}
3. 正确返回
*/
public int[] searchRange(int[] nums, int target) {
int leftBorder = getLeftBorder(nums, target);
int rightBorder = getRightBorder(nums, target);
if(leftBorder == -2 || rightBorder == -2){//情况1
return new int[]{-1,-1};
}
if(rightBorder - leftBorder > 1){//情况3
return new int[]{leftBorder + 1, rightBorder - 1};
}
return new int[]{-1,-1};//情况2(除情况1和3)
}
public int getRightBorder(int[] nums, int target){
//寻找右边界(不包括target)
int length = nums.length;
int left = 0, right = length -1;
int mid = - 1;
int rightBorder = - 2;
while(left <= right){
mid = left + (right - left)/2;
if(nums[mid] > target){
right = mid -1;
}else{
//等于的情况也包含在内,就是说如果nums[mid]=target
//left就一个一个往后移,直到移出去待找的区间
//动手画图试试看
left = mid + 1;
rightBorder = left;
}
}
return rightBorder;
}
public int getLeftBorder(int[] nums, int target){
//寻找右边界(不包括target)
int length = nums.length;
int left = 0, right = length -1;
int mid = - 1;
int leftBorder = - 2;
while(left <= right){
mid = left + (right - left)/2;
if(nums[mid] >= target){//一样,要取到等号,一个个往左移
right = mid - 1;
leftBorder = right;
}else{
left = mid + 1;
}
}
return leftBorder;
}
}