zoukankan      html  css  js  c++  java
  • Search for a Range

    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 value一定可以找到,所以,不需要判断标记是否出界

    vector<int> searchRange(vector<int>& nums, int target) {
        int beg = 0, end = nums.size() - 1, mid = 0;
        vector<int> ret = {-1, -1};
        // 查找左边界
        while (beg <= end)
        {
            mid = beg + ((end - beg) >> 1);
            if (target <= nums[mid])
                end = mid - 1;
            else
                beg = mid + 1;
        }
        
        if (nums[beg] == target)
            ret[0] = beg;
        else
            return ret;
        // 查找右边界
        end = nums.size() - 1; // 从左边界开始查找
        while (beg <= end)
        {
            mid = beg + ((end - beg) >> 1);
            if (target < nums[mid])
                end = mid - 1;
            else
                beg = mid + 1;
        }
        ret[1] = end;
        return ret;
    }
  • 相关阅读:
    计算 sql查询语句所花时间
    iframe自适应高度,以及一个页面加载多个iframe
    窗体移动API和窗体阴影API
    js复习:
    web组合查询:
    web登陆,增删改加分页。
    cookie和Session传值
    控件及其数据传输
    ASP.NET WebForm
    三月总结
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5048175.html
Copyright © 2011-2022 走看看