Description:
Given a sorted array of n integers, find the starting and ending position of a given target value.
If the target is not found in the array, return [-1, -1].
Note:
1.用二分法找两次index,时间复杂度为O(logN)
2.用二分法要注意的几点:
a.注意考虑只有一个元素的情况,所以当low==high的时候也要进入循环。
b.首尾区间是闭区间,所以当mid数不为所求数时,记得取mid+1作下界或者mid-1作上界,不然容易死循环。
Given a sorted array of n integers, find the starting and ending position of a given target value.
If the target is not found in the array, return [-1, -1].
Note:
1.用二分法找两次index,时间复杂度为O(logN)
2.用二分法要注意的几点:
a.注意考虑只有一个元素的情况,所以当low==high的时候也要进入循环。
b.首尾区间是闭区间,所以当mid数不为所求数时,记得取mid+1作下界或者mid-1作上界,不然容易死循环。
Code:
class Solution {
public:
/*
* @param A: an integer sorted array
* @param target: an integer to be inserted
* @return: a list of length 2, [index1, index2]
*/
vector<int> searchRange(vector<int> &A, int target) {
// write your code here
vector<int> result;
int low = 0;
int high = A.size() - 1;
int mid;
while (low <= high) {
mid = low + (high - low) / 2;
if (A[mid] == target && (!mid || A[mid - 1] != target)) {
result.push_back(mid);
break;
}
else if (A[mid] < target) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
low = 0;
high = A.size() - 1;
while (low <= high) {
mid = low + (high - low) / 2;
if (A[mid] == target && (mid==A.size()-1 || A[mid + 1] != target)) {
result.push_back(mid);
break;
}
else if (A[mid] > target) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
if (result.empty()) {
result.push_back(-1);
result.push_back(-1);
return result;
}
return result;
}
};