您的位置:首页 > 其它

Search for a Range

2015-08-14 14:10 232 查看
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]
.

class Solution {
public:
int helper(vector<int>& nums, int target)
{
int len = nums.size();
int left = 0;
int right = len - 1;
int pos = -1;
while(1)
{
if(nums[right] < target || nums[left] > target)
{
break;
}
if(nums[(left + right)/2] == target)
{
pos = (left + right)/2;
break;
}
if(nums[(left + right)/2] > target)
{
left = left;
right = (left + right)/2 - 1;
continue;
}
if(nums[(left + right)/2] < target)
{
left = (left + right)/2 + 1;
right = right;
continue;
}
}
return pos;
}
vector<int> searchRange(vector<int>& nums, int target)
{
int len = nums.size();
vector<int> vec;
if(len == 0)
{
vec.push_back(-1);
vec.push_back(-1);
return vec;
}
int pos = -1;
int left = 0;
int right = len - 1;

pos = helper(nums, target);
if(pos == -1)
{
vec.push_back(-1);
vec.push_back(-1);
return vec;
}
int start = pos;
int end = pos;
left = 0;
right = start;
//assert(0);
while(1)
{

if(nums[(left + right)/2] == target)
{
if((left + right)/2 == 0)
{
start = 0;
break;
}else
{
if(nums[(left + right)/2 - 1] < target)
{
start = (left + right)/2;
break;
}else
{
left = left;
right = (left + right)/2 - 1;
}
}
continue;

}
if(nums[(left + right)/2] < target)
{
left = (left + right)/2 + 1;
right = right;
continue;
}

}
//assert(0);
left = end;
right = len - 1;
//cout << start << endl;
while(1)
{
if(nums[(left + right)/2] == target)
{
if((left + right)/2 == len - 1)
{
end = len - 1;
break;
}else
{
if(nums[(left + right)/2 + 1] > target)
{
end = (left + right)/2;
break;
}else
{
left = (left + right)/2 + 1;
right = right;
}
}
continue;
}
if(nums[(left + right)/2] > target)
{
left = left;
right = (left + right)/2 - 1;
continue;
}

}
//assert(0);
//cout << end << endl;
vec.push_back(start);
vec.push_back(end);
return vec;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: