给定按升序排序的整数数组,找到给定目标值的起始和终止位置。 您的算法的运行时复杂度必须是O(log n)的顺序。

/**
 * 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 low_i,low_j,high_i,high_j;
    int low_middle,high_middle;
    low_i = 0;
    low_j = numsSize-1;
    *returnSize=2;
    int *res = (int*)calloc(2, sizeof(int));
    res[0] = -1;
    res[1] = -1;
    while(low_i<=low_j)
    {
        low_middle = (low_i+low_j)/2;
        if(nums[low_middle]==target)
        {
            if(low_middle==0) break;
            else
            {
                if(nums[low_middle-1]target) break;
                else high_i = high_middle+1;
            }
        }
        else
            high_j = high_middle-1;
    }
    res[0] = low_middle;
    res[1] = high_middle;
    return res;
    
}

思路:使用二分查找,查找目标值的低位下标和高位下标。设置4个变量,代表查找低位下标和高位下标的起始位置。不断二分查找,最终找到目标!

/**
 * 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 low_i,low_j,high_i,high_j;
    int low_middle,high_middle;
    low_i = 0;
    low_j = numsSize-1;
    *returnSize=2;
    int *res = (int*)calloc(2, sizeof(int));
    res[0] = -1;
    res[1] = -1;
    while(low_i<=low_j)
    {
        low_middle = (low_i+low_j)/2;
        if(nums[low_middle]==target)
        {
            if(low_middle==0) break;
            else
            {
                if(nums[low_middle-1]<target) break;
                else low_j = low_middle;
            }
        }
        else if(nums[low_middle]<target)
            low_i = low_middle+1;
        else
            low_j = low_middle-1;
    }
    if(nums[low_middle]!=target) 
        return res;
    high_i = low_middle;
    high_j = numsSize-1;
    while(high_i<=high_j)
    {
        high_middle = (high_i+high_j)/2;
        if(nums[high_middle]==target)
        {
            if(high_middle==numsSize-1) break;
            else
            {
                if(nums[high_middle+1]>target) break;
                else high_i = high_middle+1;
            }
        }
        else
            high_j = high_middle-1;
    }
    res[0] = low_middle;
    res[1] = high_middle;
    return res;
    
}

    原文作者:排序算法
    原文地址: https://blog.csdn.net/lt77701/article/details/71482144
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞