• 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] andtarget value 8,

    return [3, 4].

     

    思路:本题还是在考察二分查找法的使用。首先使用二分查找找到一个target的位置,该位置将数组分为两个子数组,左边的子数组都是小于等于target,右边的子数组都是大于等于target。可以再利用二分查找,分别找到target的边界。代码如下:

    /**
     * Return an arrayof size *returnSize.
     * Note: Thereturned array must be malloced, assume caller calls free().
     */
    int* searchRange(int* nums, int numsSize, int target, int* returnSize)
    {
        int resleft, resright;
        int left, right;
        int mid = -1;
        int resmid;
     
        left = 0; right = numsSize - 1;
        while(left <= right)
        {
            mid = left + (right-left)/2;
            if(nums[mid] == target)
            {
                break;
            }
            if(nums[mid] > target)
            {
                right -= 1;
            }
            else
            {
                left += 1;
            }
        }
     
        if(left > right)
        {
            int *res = calloc(2, sizeof(int));
            res[0] = -1;
            res[1] = -1;
            *returnSize = 2;
            return res;
        }
     
        left = 0;
        right = mid;
        while(left < right)
        {
            resmid = left + (right-left)/2;
            if(nums[resmid] < target)
            {
                left = resmid+1;
            }
            else
            {
                right = resmid;
            }
        }
        resleft = left;
     
        left = mid;
        right = numsSize - 1;
        while(left <= right)
        {
            resmid = left + (right-left)/2;
            if(nums[resmid] == target)
            {
                left = resmid+1;
            }
            else
            {
                right = resmid-1;
            }
        }
        resright = right;
     
        int *res = calloc(2, sizeof(int));
        res[0] = resleft;
        res[1] = resright;
        *returnSize = 2;
        return res;
    }


  • 相关阅读:
    16_基于FPGA的DA_TLC5615驱动输出
    17_IIC协议与FPGA驱动AT24C04
    14_基于FPGA的DSS与嵌入式逻辑分析仪的调用
    11_基于FPGA的按键计数器
    08_基于FPGA的测頻计的设计
    15_基于FPGA的AD_TLC549采集模拟信号
    13_基于FPGA的液晶1602显示
    09_基于FPGA驱动蜂鸣器唱歌
    HTML 综合案例简陋的相亲网站界面
    go 语言里面的 & 和 *
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/7247144.html
Copyright © 2020-2023  润新知