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]
.
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 l = 0;
int r = n - 1;
int m = 0;
vector<int> res(2);
res[0] = -1;
res[1] = -1;
while(l <= r){
m = (l + r)/2;
if(A[m] == target){
break;
}
if(A[m] > target){
r = m - 1;
}
else{
l = m + 1;
}
}
if(A[m] == target){
int left = m;
while(left >=0 &&A[left] == target){
left--;
}
int right = m;
while(right < n &&A[right] == target){
right++;
}
res[0] = left + 1;
res[1] = right - 1;
}
return res;
}
};
哎,任何时候不能偷懒啊,前几天M家电面考到了一个我偷懒没有认真考虑的问题,昨天algorithm考试又考到了这道题,擦了。
下面是准确的O(lgn)的解法。
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> res(2);
res[0] = binarySearch(A, n, target - 1) + 1;
res[1] = binarySearch(A, n , target);
if(res[1] == -1 || A[res[1]] != target){
res[0] = -1;
res[1] = -1;
}
return res;
}
int binarySearch(int A[], int n, int target){
int l = 0;
int r = n -1;
int m = (l+r)/2;
int ret = -1;
while(l<=r){
if(A[m] > target){
r = m - 1;
m = (l+r)/2;
}
else{
ret = m;
l = m + 1;
m = (l+r)/2;
}
}
return ret;
}
};