题目:
Given a sorted array of integers, 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
给定一个有序整型数组,找出给定目标值的其实和终止位置。时间复杂度要求O(log n).
如果目标值不存在,则返回[-1, -1].。
思路:
最简单的思路是:在普通的二分查找到目标值之后,向左右扩展。
但是,这样算法有可能会退化到O(n)。
例如,在“8 8 8 8 8 8 8 8 8 8 8 8 8 ... 8”中搜“8”。
代码1(虽然AC,但是不好):
class Solution {
public:
vector<int> searchRange(int A[], int n, int target)
{
vector<int> result;
if(n == 0)
return result;
int begin = 0 ;
int end = n - 1;
int index = -1;
while(begin <= end)
{
int mid = (begin + end) / 2;
if(A[mid] == target)
{
index = mid;
break;
}
if(A[mid] < target)
begin = mid + 1;
else
end = mid - 1;
}
if(index == -1)
{
result.push_back(-1);
result.push_back(-1);
return result;
}
int index1 = index;
while(index1 >=0 && A[index1] == target)
index1--;
result.push_back(index1+1);
while(index < n && A[index] == target)
index++;
result.push_back(index-1);
return result;
}
};
代码2:
class Solution {
public:
vector<int> searchRange(int A[], int n, int target)
{
vector<int> result(2,-1);
int begin = 0 , end = n - 1;
//重点是这个=,当begin=end时,还要再循环一次才能找到确定位置
while(begin <= end)
{
int mid = (begin + end) / 2;
if(A[mid] < target)
begin = mid + 1;
else
end = mid - 1;
}//1 2 3 4 5中查找3,结果是begin = 2 , end = 1
if(A[begin] != target)
return result;
else
result[0] = begin;
//begin = 0;
end = n - 1;
while(begin <= end)
{
int mid = (begin + end) / 2;
if(A[mid] > target)
end = mid - 1;
else
begin = mid + 1;
}
result[1] = end;
return result;
}
};