题目:
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
思路:
对二分法进行改造。改造后,正常情况下,search_first中的left会指向重复元素的第1个元素;search_last中的right会指向重复元素中的最后一个元素。
正常情况举例。例如,nums={1,2,3,5,5,5,7,8,9},target=5。最终搜索结果如下:
对于边界问题,考虑两种特殊情况就好了,如下:
- 情况1:当nums={2,2},target=3时,search_first中的left会大于nums.size()-1,越界。
- 情况2:当nums={2,2},target=1时,search_last中的right会小于0,越界。
防备好这两种情况就好。
代码实现:
class Solution {
public:
int search_first(vector<int>& nums, int target){
if (nums.size() <= 0){
return -1;
}
int left = 0;
int right = nums.size()-1;
int mid;
while (left <= right){
mid = left + (right-left)/2;
if (nums[mid] >= target){
right = mid - 1;
}else{
left = mid + 1;
}
}
if (left < nums.size() && nums[left] == target){
return left;
}
return -1;
}
int search_last(vector<int>& nums, int target){
if (nums.size() <= 0){
return -1;
}
int left = 0;
int right = nums.size()-1;
int mid;
while (left <= right){
mid = left + (right-left)/2;
if (nums[mid] > target){
right = mid - 1;
}else{
left = mid + 1;
}
}
if (right >= 0 && nums[right] == target){
return right;
}
return -1;
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans;
if (nums.size() <= 0){
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
ans.push_back(search_first(nums, target));
ans.push_back(search_last(nums, target));
return ans;
}
};
discuss:
// part 1和part 2是镜像代码
class Solution {
public:
vector<int> searchRange(vector<int>& A, int target) {
if (A.empty()) return {-1, -1};
int i = 0, j = A.size() - 1;
vector<int> ret(2, -1);
// part 1
while (i < j){
int mid = (i + j) / 2;
if (A[mid] < target){
i = mid + 1;
}else {
j = mid;
}
}
if (A[i] != target){ // 一个也没找到的情况
return ret;
}else{
ret[0] = i;
}
// part 2
j = A.size() - 1;
while (i < j){
int mid = (i + j + 1) / 2; //使得mid往右偏
if (A[mid] > target){
j = mid - 1;
}else{
i = mid;
}
}
ret[1] = j;
return ret;
}
};