您的位置:首页 > 其它

leetcode_34——Search for a Range(二分查找)

2015-05-27 15:20 441 查看

Search for a Range

Total Accepted: 43717 Total Submissions: 158420My Submissions
Question Solution

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

Have you met this question in a real interview?
Yes

No

Discuss

这道题直接采用二分查找就可以,只是有一点我没有接着做下去,就是第一次采用二分查找在已排好序的数列中找到那个数,其实还应该接着分别采用二分查找来找

那个两边的端点,但是由于直接已经可以AC了,所以我没有接着做下去了

#include<iostream>
#include<vector>
using namespace std;
vector<int> searchRange(vector<int>& nums, int target) {
int len=nums.size();
int i=0;
int j=len;
int flag=0;
int locat;
while(i!=j)
{
int z=(i+j)/2;
if(nums[z]==target)
{flag=1;locat=z;break;}

if(target>nums[z])
i=z+1;
else
j=z;
}
vector<int> last_reault;
if(flag==0)
{
last_reault.push_back(-1);
last_reault.push_back(-1);
}
else
{
int a=locat,b=locat;
for(int i=locat;i<len;i++)
if(nums[i]==target)
a=i;
for(int j=locat;j>=0;j--)
if(nums[j]==target)
b=j;
last_reault.push_back(b);
last_reault.push_back(a);
}
return last_reault;
}
int main()
{

}


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