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]
.
public class Solution {
int findStart(int[] A, int target){
int start=0;
while(A.length>1){
int half=A.length/2-1;
if(A[half]<target){
A=Arrays.copyOfRange(A, half+1, A.length);
start+=half+1;
}
// A[half]>target is not possible
// So is A[half]==target
else
A=Arrays.copyOfRange(A, 0, half+1);
}
return start;
}
int findEnd(int[] A, int target){
int end=0;
while(A.length>1){
int half=A.length/2-1;
if(A[half+1]>target)
A=Arrays.copyOfRange(A, 0, half+1);
// A[half+1]<target is not possible
// So is A[half+1]==target
else{
A=Arrays.copyOfRange(A, half+1, A.length);
end+=half+1;
}
}
return end;
}
public int[] searchRange(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int start=0, end;
while(A.length>1){
int half=A.length/2-1;
if(A[half]<target){
A=Arrays.copyOfRange(A, half+1, A.length);
start+=half+1;
}
else if(A[half]>target){
A=Arrays.copyOfRange(A, 0, half+1);
}
// A[half]==target
else{
if(A[half+1]==target){
end=start+half+1+findEnd(Arrays.copyOfRange(A, half+1, A.length), target);
start+=findStart(Arrays.copyOfRange(A, 0, half+1), target);
}
else{
end=start+half;
start+=findStart(Arrays.copyOfRange(A, 0, half+1), target);
}
return new int[]{start, end};
}
}
if(A[0]==target)
return new int[]{start, start};
return new int[]{-1,-1};
}
}
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
int begin, end, mid, first, last;
vector<int> res;
begin = 0; end = n-1;
// find start
while(begin < end)
{
mid = begin + (end-begin)/2;
if(target <= A[mid])
end = mid;
else
begin = mid+1;
}
first = target == A[begin]?begin:-1;
last = -1;
// find
if(first!=-1)
{
end = n-1;
while(begin < end)
{
mid = begin + (end-begin+1)/2;
if(target >= A[mid])
begin = mid;
else
end = mid-1;
}
last = begin;
}
res.push_back(first);
res.push_back(last);
return res;
}
};