您的位置:首页 > 其它

leetcode笔记:34. Search for a Range

2017-02-17 11:09 363 查看
Given an array of integers sorted in ascending order, 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]
.

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n=nums.size();
vector<int> ans;
if(n==0){
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
int left1=0,right1=n,left2=0,right2=n;
int left,right;
int mid1,mid2;
while(left1<right1){
mid1=(left1+right1)/2;
if(target<=nums[mid1]){
right1=mid1;
}
else{
left1=mid1+1;
}
}
//cout<<left1<<endl;
//cout<<right1<<endl;
if(right1>=n||nums[right1]!=target){
left=-1;
}
else{
left=left1;
}

while(left2<right2){
mid2=(left2+right2)/2;
if(target>=nums[mid2]){
left2=mid2+1;
}
else{
right2=mid2;
}
}
//cout<<left2<<endl;
//cout<<right2<<endl;
if(right2-1>=n||nums[right2-1]!=target){
right=-1;
}
else{
right=right2-1;
}

ans.push_back(left);
ans.push_back(right);
return ans;
}
};

道理很简单,求左边界,相等就往左,最后停留在左边第一个target点。右边界,相等就往右,最后停留在右边第一个大于target的点。
值得注意的是如果最大的都小于target,要特殊处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: