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]
.
此题在何海涛的书第38题。利用二分法,俩次。分别找左右索引地址。如果只用一次二分,利用一步一步移动寻找,在全为target时时间复杂度为o(n)!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int find_right(int A[], int n, int target);
int find_left(int A[], int n, int target);
vector<int> searchRange(int A[], int n, int target) ;
int main()
{
int A[] = {5, 8, 8, 8, 8, 10} ;
vector<int> res = searchRange(A,6,6);
cout<<res[0]<<endl;
cout<<res[1]<<endl;
return 0;
}
vector<int> searchRange(int A[], int n, int target)
{
vector<int> pos(2);
pos[0] = find_left(A,n,target);
pos[1] = find_right(A,n,target);
return pos;
}
int find_left(int A[], int n, int target)
{
if(n <= 0)return -1;
int right = n-1;
int left = 0;
int mid;
while(left <= right)
{
mid = (left + right)/2;
if (A[mid] == target)
{
if(mid >= 1 && A[mid-1] == target)
{
right = mid -1;
}
else
{
return mid;
}
}
else if(A[mid] > target)
{
right = mid -1;
}
else
{
left = mid + 1;
}
}
return -1;
}
int find_right(int A[], int n, int target)
{
if(n <= 0)return -1;
int right = n-1;
int left = 0;
int mid;
while(left <= right)
{
mid = (left + right)/2;
if (A[mid] == target)
{
if(mid < n-1 && A[mid+1] == target)
{
left = mid +1;
}
else
{
return mid;
}
}
else if(A[mid] > target)
{
right = mid -1;
}
else
{
left = mid + 1;
}
}
return -1;
}