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

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4]. spa

題目簡述:給定一個有序的整型數組,找出給定的目標值的start和end下標。code

算法的時間複雜度必須是O(log n)blog

如目標值沒有發現,返回[-1,-1].get

如給定一個數組[5,7,7,8,8,10],給定目標值8,it

返回[3,4]。io

思路:event

  按照折半查找的方法查找到給定的目標值,獲得相應的下標,在下標的兩側進行查找,找到相同的值.

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
相關文章
相關標籤/搜索