题目:Search for a Range
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]
.
Given [5, 7, 7, 8,8, 8, 10]
and target value 8,
return [3, ,5]
.
思路:
(1)开辟一个存储下标的数组tmp;
(2)二分法进行查找,如果找到目标就向数组中进行存储下标,并判断前后元素是否等于目标,
如果中间元素的前一个元素等于目标,find(nums,low,m-1,tmp,top,target);
如果中间元素的后一个元素等于目标,find(nums,m+1,h,tmp,top,target);
(3)如果中间元素大于目标,在目标在左边的区间;find(nums,low,m-1,tmp,top,target);
(4)如果中间元素小于目标,在目标在右边的区间;find(nums,m+1,h,tmp,top,target);
(5)tmp中无元素,返回[-1,-1];
tmp中一个元素x,返回[x,x];
tmp中大于一个元素,返回tmp的第一个元素和最后一个元素。
代码:
void find(int* nums,int low,int hig,int* tmp,int* top,int target);
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
int top=-1;
int* ret=(int*)malloc(sizeof(int)*2);
ret[0]=-1;
ret[1]=-1;
int tmp[numsSize];
memset(tmp,0,numsSize*sizeof(int));
find(nums,0,numsSize-1,&tmp,&top,target);
if(top==0)
{
ret[0]=tmp[top];
ret[1]=ret[0];
}
else if(top>=1)
{
ret[0]=tmp[0];
ret[1]=tmp[top];
}
if(top==-1)
{
*returnSize=0;
}
else if(top==0)
{
*returnSize=1;
}
else if(top >=1 )
{
*returnSize=top+1;
}
//free(&tmp);
*returnSize=2;
return ret;
}
void find(int* nums,int low,int hig,int* tmp,int* top,int target)
{
int l=low;
int h=hig;
int m=(l+h)/2;
int ll=0,hh=0;
if(l>h) return -1;
if(nums[m] == target)
{
if(nums[m-1] == target )
{
find(nums,low,m-1,tmp,top,target);
}
tmp[++(*top)]=m;
if(nums[m+1] == target )
{
find(nums,m+1,h,tmp,top,target);
}
}
else if(nums[m] > target ) find(nums,low,m-1,tmp,top,target);
else if(nums[m] < target ) find(nums,m+1,h,tmp,top,target);
}