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].
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].
#include <iostream>
#include <vector>
using namespace std;
//思路。二分查找的升级版本。
//1.先找到tar的位置,那么它的左边界肯定在左边,右边界肯定在右边
//2.分别对tar的左右两边进行二分查找,找到对应的左右边界
int findIndex(int a[],int first,int last,int tar,bool isLeft)
{
if(first > last)
return -1;
int mid = (first+last)/2;
if(a[mid] == tar)
{
//分别对左右进行二分查找,找到对应的Pos
int pos = isLeft?findIndex(a,first,mid-1,tar,isLeft):findIndex(a,mid+1,last,tar,isLeft);
return pos == -1?mid:pos;
}
else if(a[mid] < tar)
{
return findIndex(a,mid+1,last,tar,isLeft);
}
else
{
return findIndex(a,first,mid-1,tar,isLeft);
}
}
vector<int> searchRange(int a[],int n,int tar)
{
vector<int> ret(2,-1);
if(n<=0) return ret;
if(tar<a[0] || tar > a[n-1]) return ret;
bool isLeft = true;
int leftIdx = findIndex(a,0,n-1,tar,isLeft);
if (leftIdx == -1) return ret;
int rightIdx = findIndex(a,0,n-1,tar,!isLeft);
ret[0] = leftIdx;
ret[1] = rightIdx;
return ret;
}
void main()
{
int a[] = {1,1,2,2,3,3,3,4,4};
int len = sizeof(a)/sizeof(int);
for(int i=0;i<len;i++)
{
printf("%d ",a[i]);
}
printf("\n");
vector<int> ret = searchRange(a,len,3);
for(unsigned int i=0;i<ret.size();i++)
{
printf("%d ",ret[i]);
}
printf("\n");
}
本文介绍了如何在一个已排序的整数数组中找到指定目标值的起始和结束索引位置,算法的时间复杂度需为O(logn)。若目标值未出现在数组中,则返回[-1, -1]。通过实现二分查找的升级版本,首先定位到目标值的位置,然后分别向左右两侧递归查找,最终确定目标值的边界。
3246

被折叠的 条评论
为什么被折叠?



