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]
.
二分法。一开始没完全理解题意,误以为返回两个相邻或相等的index的情况就可以了。考虑以下情况:
Given [5,7,7,8,8,8] Target Value: 8
return [3,5]
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result;
result.push_back(findPosition(A,0,n-1,target,true));
result.push_back(findPosition(A,0,n-1,target,false));
return result;
}
int findPosition (int A[], int begin, int end, int target, bool leftFlag)
{
if(begin>end) return -1;
int middle = (begin + end)/2;
if(A[middle] == target)
{
int position;
if(leftFlag)
{
position = findPosition(A,begin,middle-1,target,leftFlag);
}
else
{
position = findPosition(A,middle+1,end,target,leftFlag);
}
return (position == -1)?middle:position;
}
else if(A[middle]<target)
{
return findPosition(A,middle+1,end,target,leftFlag);
}
else
{
return findPosition(A,begin,middle-1,target,leftFlag);
}
}
};