Search for a Range

本文介绍了如何在一个已排序的整数数组中找到指定目标值的起始和结束索引位置,算法的时间复杂度需为O(logn)。若目标值未出现在数组中,则返回[-1, -1]。通过实现二分查找的升级版本,首先定位到目标值的位置,然后分别向左右两侧递归查找,最终确定目标值的边界。
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].

#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");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值