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;
    }


  • 相关阅读:
    C++库---json
    C++之单例模式
    mysql之字段(整形、字符串等)
    C++之数据类型,容器
    C++文件操作,判断两个文件内容是否相等(被修改)
    (转)mysql之index(索引)
    Django中的日期和时间格式 DateTimeField
    有关Django的smallDemo
    mysql 快速生成百万条测试数据
    从输入URL到页面加载发生了什么
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/7247144.html
Copyright © 2011-2022 走看看