题目
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].
标签
Array、Binary Search
难度
适中
分析
题目意思是给定一个排好序的整型数组和一个整型,然后找到这个整型在这个数组的起始位置和结束位置,并返回对应的下标,如果没有找到,返回[-1,-1]。这里的做法是,从数组开头查找起始位置,从数组末尾查找结束位置。
C代码实现
/**
* 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 i=0;
int start=0, end=0;
bool startFlag = false;
bool endFlag = false;
int * array = (int *)malloc(sizeof(int)*2);
for(i=0; i<numsSize; i++)
{
if(target == nums[i])
{
start = i;
startFlag = true;
break;
}
}
for(i=numsSize-1; i>=0; i--)
{
if(target == nums[i])
{
end = i;
endFlag = true;
break;
}
}
*returnSize = 2;
if((true ==startFlag) && (true ==endFlag))
{
array[0] = start;
array[1] = end;
}
else
{
array[0] = -1;
array[1] = -1;
}
return array;
}