您的位置:首页 > 其它

LeetCode 34.Search for a Range

2015-02-17 12:00 387 查看
题目:

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]
.
分析与解答:看到题目就在想,这不就是STL里面的equalrange吗。依然是二分查找,只是查找停止的条件更严格了一些。可以分两次查找。第一次找左边界,第二次找右边界。

class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
int left = 0, right = n;
while(left != right) {
int mid = left + (right - left) / 2;
if(A[mid] >= target)
right = mid;
else
left = mid + 1;
}
int left1 = left;
left = 0, right = n;
while(left != right) {
int mid = left + (right - left) / 2;
if(A[mid] > target)
right = mid;
else
left = mid + 1;
}
if(A[left1] != target)//没找到target
return vector<int>{-1,-1};
else
return vector<int>{left1,left - 1};
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: