zoukankan      html  css  js  c++  java
  • 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;
    }


  • 相关阅读:
    hello world!
    react(一):组件的生命周期
    position和BFC
    继承
    绕不开的this
    js世界这么大,闭包想看看
    js中数组常用方法总结
    Appium混合应用测试
    手机APP兼容性测试
    运行monitor提示需要安装旧JAVA SE 6运行环境
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/7247144.html
Copyright © 2011-2022 走看看