zoukankan      html  css  js  c++  java
  • leetcode: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].

     

    大致题意:找到值为target的下标范围

    vector<int> searchRange(int A[], int n, int target) {
        int l,r,mid;
        std::vector<int> ans;
        l=0;
        r=n-1;
        //找到第一个不小于target的位置
        while (l<=r)
        {
            mid=(l+r)>>1;
            if (A[mid]>=target)
                r=mid-1;
            else l=mid+1;
        }
        if (A[l]==target)
            ans.push_back(l);
        else{
            ans.push_back(-1);
            ans.push_back(-1);
            return ans;
        }
        l=0;
        r=n-1;
        //找到第一个大于target的位置
        while (l<=r)
        {
            mid=(l+r)>>1;
            if (A[mid]>target)
                r=mid-1;
            else l=mid+1;
        }
        ans.push_back(l-1);
        return ans;
    }
  • 相关阅读:
    软件开发规范
    内置模块
    自定义模块
    装饰器 递归
    内置函数 闭包
    生成器 推导式
    函数名运用 新版格式化输出 迭代器
    函数进阶
    pycharm快捷键
    移动端必测点
  • 原文地址:https://www.cnblogs.com/mintmy/p/4190597.html
Copyright © 2011-2022 走看看