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] and target value 8,
    return [3, 4].

    题目简述:给定一个有序的整型数组,找出给定的目标值的start和end下标。

    算法的时间复杂度必须是O(log n)

    如目标值没有发现,返回[-1,-1].

    如给定一个数组[5,7,7,8,8,10],给定目标值8,

    返回[3,4]。

    思路:

      按照折半查找的方法查找到给定的目标值,得到相应的下标,在下标的两侧进行查找,找到相同的值.

    int* searchRange(int* nums, int numsSize, int target, int* returnSize) 
    {
        int *res=(int*)malloc(sizeof(int)*2);
        for(int i=0;i<2;i++)res[i]=-1;
        int low=0;
        int high=numsSize-1;
        int start=-1,end=-1;
        if(low>high)return res;
        *returnSize=2;
        while(low<=high)
        {
            int mid=(low+high)/2;
            if(nums[mid]>target)
            {
                high=mid-1;
            }
            else if(nums[mid]<target)
            {
                low=mid+1;
            }
            else{
                start=mid;
                end=mid;
                while(start>low&&nums[start-1]==nums[start])start--;
                while(end<high&&nums[end+1]==nums[end])end++;
                res[0]=start;
                res[1]=end;
                return res;
            }
        }
        return res;
    }
    View Code
  • 相关阅读:
    SpringBoot-Swagger
    SpringBoot-Shiro
    SpringBoot-SpringSecurity
    SpringBoot-整合数据库
    SpringBoot-Web开发
    SpringBoot-基础
    SpringMVC-文件上传和下载
    SpringMVC-拦截器
    SpringMVC-AJAX
    Eclipse的安装
  • 原文地址:https://www.cnblogs.com/lichao-normal/p/6151447.html
Copyright © 2011-2022 走看看