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]
.
[Analysis]
先用二分找到任意一个target,假设下标为mid,然后分为A[left:mid]和A[mid:right]两个数组,再分别使用二分查找边界。
[Solution]
class Solution {
public:
// search left bound
int searchLeft(int A[], int n, int left, int right, int target){
int mid = left + (right-left)/2;
while(left <= right){
mid = left + (right-left)/2;
if(A[mid] < target){
left = mid+1;
}
else if(A[mid] > target){
right = mid-1;
}
else{
if(mid == 0 || (mid > 0 && A[mid-1] != target)){
return mid;
}
else{
right = mid-1;
}
}
}
return -1;
}
// search right bound
int searchRight(int A[], int n, int left, int right, int target){
int mid = left + (right-left)/2;
while(left <= right){
mid = left + (right-left)/2;
if(A[mid] < target){
left = mid+1;
}
else if(A[mid] > target){
right = mid-1;
}
else{
if(mid == n-1 || (mid < n-1 && A[mid+1] != target)){
return mid;
}
else{
left = mid+1;
}
}
}
return -1;
}
// search range
vector searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// search target
int left = 0, right = n-1, mid;
while(left <= right){
mid = left + (right-left)/2;
if(A[mid] < target){
left = mid+1;
}
else if(A[mid] > target){
right = mid-1;
}
else{
break;
}
}
// search left bound and right bound
int leftBound = -1, rightBound = -1;
if(mid >= 0 && mid <= n-1 && left <= right){
// search left bound
if(mid > 0 && A[mid-1] == target){
leftBound = searchLeft(A, n, left, mid, target);
}
else{
leftBound = mid;
}
// search right bound
if(mid < n-1 && A[mid+1] == target){
rightBound = searchRight(A, n, mid, right, target);
}
else{
rightBound = mid;
}
}
// set result
vector res;
res.push_back(leftBound);
res.push_back(rightBound);
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客