Leetcode 34. Search for a Range

題目

Given an array of integers sorted in ascending order, 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].

分析

給定一個排序數(shù)組,尋找一個給定值的開始位置和結束位置,如果沒有該值,返回(-1,-1)
由于時間需要O(log n),所以需要使用二分查找,直到找到特定值,然后再周圍搜索所有等于該值的位置,如果沒有直接返回-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 p=0,q=numsSize-1;
    int *ans=(int *)malloc(2*sizeof(int));
    while(p<q)
    {
        if(nums[(p+q)/2] > target) q = (p+q)/2-1;
        else if(nums[(p+q)/2] < target) p = (p+q)/2+1;
        else break;
       // printf("%d %d\n",p,q);
    }
    if(p>q||(p==q&&nums[p]!=target))
    {
        ans[0]=-1;
        ans[1]=-1;
        *returnSize=2;
    }
    else
    {
        p=(p+q)/2;
        q=p;
        while(p>0)
        {
            if(nums[p]==nums[p-1]) p--;
            else break;
        }
        while(q<numsSize-1)
        {
            if(nums[q]==nums[q+1])q++;
            else break;
        }
        ans[0]=p;
        ans[1]=q;
        *returnSize=2;
    }
    return ans;
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容