给定按升序排序的整数数组,找到给定目标值的起始和终止位置。 您的算法的运行时复杂度必须是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 high_i = high_middle+1;
            }
        }
        else
            high_j = high_middle-1;
    }
    res[0] = low_middle;
    res[1] = high_middle;
    return res;
    
}

你可能感兴趣的:(算法灵感)