您的位置:首页 > 其它

LeetCode *** 34. Search for a Range

2016-04-17 23:13 399 查看
题目:

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]
.

分析:

38.1%,呵呵哒。。。这种二分的题我也能做成这样。。。。

代码:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.size()<1)return vector<int>{-1,-1};
int size=nums.size();
int low=0,high=size-1;

vector<int> res;
while(low<high){

int mid=(low+high)/2;
if(nums[mid]==target){
low=mid-1,high=mid+1;
while(low>=0&&nums[low]==target)
if(nums[low]==target)low--;
while(high<size&&nums[high]==target)
if(nums[high]==target)high++;
res.push_back(++low);
res.push_back(--high);
break;
}
if(nums[mid]>target){
high=mid;
}
else low=mid+1;
}

if(res.empty()){
if(nums[low]!=target)return vector<int>{-1,-1};
else {
res.push_back(low);
res.push_back(low);
}
}
return res;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: