1. 题目
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].
2. 思路
基于二分搜索进行。分别查找最低位和最高位。
找最低位是,每次找到了之后,不是立刻退出,而是继续在左侧进一步查找,直到再也找不到的时候,返回上一次找到的位置。
找最高位类似。
3. 代码
耗时:9ms
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ret;
int i = bsearch_low(nums, 0, nums.size(), target);
ret.push_back(i);
if (i == -1) {
ret.push_back(-1);
return ret;
}
int j = bsearch_high(nums, 0, nums.size(), target);
ret.push_back(j);
return ret;
}
int bsearch(vector<int>& nums, int i, int j, int target) {
if (i >= j) { return -1; }
if (i+1 == j) { return nums[i] == target ? i : -1; }
int k = i + (j - i) / 2;
if (nums[k] == target) {
return k;
} else if (nums[k] < target) {
return bsearch(nums, k+1, j, target);
} else {
return bsearch(nums, i, k, target);
}
}
int bsearch_low(vector<int>& nums, int i, int j, int target) {
int k = -1;
while (true) {
int n = bsearch(nums, i, j, target);
if (n == -1) {
return k;
} else {
j = n;
k = n;
}
}
}
int bsearch_high(vector<int>& nums, int i, int j, int target) {
int k = -1;
while (true) {
int n = bsearch(nums, i, j, target);
if (n == -1) {
return k;
} else {
i = n + 1;
k = n;
}
}
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。