Leecode-34
这道题核心算法就是二分搜索,与普通的二分搜索不同之处是要选出边界位置。上代码
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = 0, right = nums.length - 1;
int left1 = 0, right1 = nums.length - 1;
int[] ans = new int[2];
// 搜索区间为 [left, right]
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
// 搜索区间变为 [mid+1, right]
left = mid + 1;
} else if (nums[mid] > target) {
// 搜索区间变为 [left, mid-1]
right = mid - 1;
} else if (nums[mid] == target) {
// 收缩右侧边界
right = mid - 1;
}
}
while (left1 <= right1) {
int mid = left1 + (right1 - left1) / 2;
if (nums[mid] < target) {
// 搜索区间变为 [mid+1, right]
left1 = mid + 1;
} else if (nums[mid] > target) {
// 搜索区间变为 [left, mid-1]
right1 = mid - 1;
} else if (nums[mid] == target) {
// 收缩左侧边界
left1 = mid + 1;
}
}
// 检查出界情况
if (left >= nums.length || nums[left] != target){
ans[0] = -1;
ans[1] = -1;
return ans;
}
ans[0] = left;
ans[1] = left1 - 1 ;
return ans;
}
}
两个while循环分别找左侧边界值和右侧边界值。