链接:http://leetcode.com/onlinejudge#question_34
原题:
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]
.
思路:用二分查找,如果找到,再用二分查找分别找左边界和右边界,所以复杂度是log(n)
代码:
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 left = 0;
int right = n - 1;
vector<int> vec(2, -1);
while (left <= right) {
int mid = (left + right) / 2;
if (A[mid] < target)
left = mid + 1;
else if (A[mid] > target)
right = mid - 1;
else {
vec[0] = leftBound(A, left, mid, target);
vec[1] = rightBound(A, mid, right, target);
break;
}
}
return vec;
}
private:
int leftBound(int A[], int left, int right, int target) {
int min = right;
int i = left;
int j = right;
while (i <= j) {
int mid = (i + j) / 2;
if (A[mid] < target)
i = mid + 1;
else if (A[mid] > target)
j = mid - 1;
else {
if (mid < min)
min = mid;
j = mid - 1;
}
}
return min;
}
int rightBound(int A[], int left, int right, int target) {
int max = left;
int i = left;
int j = right;
while (i <= j) {
int mid = (i + j) / 2;
if (A[mid] < target)
i = mid + 1;
else if (A[mid] > target)
j = mid - 1;
else {
if (mid > max)
max = mid;
i = mid + 1;
}
}
return max;
}
};