您的位置:首页 > 其它

[leetcode] Search for a Range

2015-07-15 22:58 381 查看
From : https://leetcode.com/problems/search-for-a-range/
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]
.

Hide Tags
Array Binary
Search

Hide Similar Problems
(M) Search Insert Position

Solution :

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int start=0, end=nums.size()-1;
vector<int> ans(2);
ans[0]=ans[1]=-1;
while(start <= end) {
int mid = (start+end)>>1;
if(nums[mid] == target) {
for(int i=mid; i>=start; i--) {
if(nums[i] == target) {
ans[0] = i;
}
}
for(int i=mid; i<=end; i++) {
if(nums[i] == target) {
ans[1] = i;
}
}
break;
}
if(nums[mid] > target) {
end = mid-1;
} else {
start = mid+1;
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: