lichao_normal

导航

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].

题目简述:给定一个有序的整型数组,找出给定的目标值的start和end下标。

算法的时间复杂度必须是O(log n)

如目标值没有发现,返回[-1,-1].

如给定一个数组[5,7,7,8,8,10],给定目标值8,

返回[3,4]。

思路:

  按照折半查找的方法查找到给定的目标值,得到相应的下标,在下标的两侧进行查找,找到相同的值.

int* searchRange(int* nums, int numsSize, int target, int* returnSize) 
{
    int *res=(int*)malloc(sizeof(int)*2);
    for(int i=0;i<2;i++)res[i]=-1;
    int low=0;
    int high=numsSize-1;
    int start=-1,end=-1;
    if(low>high)return res;
    *returnSize=2;
    while(low<=high)
    {
        int mid=(low+high)/2;
        if(nums[mid]>target)
        {
            high=mid-1;
        }
        else if(nums[mid]<target)
        {
            low=mid+1;
        }
        else{
            start=mid;
            end=mid;
            while(start>low&&nums[start-1]==nums[start])start--;
            while(end<high&&nums[end+1]==nums[end])end++;
            res[0]=start;
            res[1]=end;
            return res;
        }
    }
    return res;
}
View Code

 

posted on 2016-12-09 20:36  lichao_normal  阅读(71)  评论(0编辑  收藏  举报