zoukankan      html  css  js  c++  java
  • leetcode@ [34] Search for a Range (STL Binary Search)

    https://leetcode.com/problems/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].

    明显的,这道题需要二分查找。实际上STL上已经为我们实现好了 二分查找 函数的接口。对于“vector”容器,我们可以利用“lower_bound” 查找 目标数值 target 第一次出现的位置。如果原数组中并不存在这个 target,lower_bound会返回第一个比target值大的位置。利用lower_bound函数获取 target 在原数组的位置:auto p = lower_bound(vec.begin(), vec.end(), target);而类似的函数upper_bound则会返回第一个比target大的位置。注意:auto p 在这里是vector 迭代器类型,转换成数字下表为 idx = p - vec.begin();

    代码如下:

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            auto p1 = lower_bound(nums.begin(), nums.end(), target);
            
            auto p2 = upper_bound(nums.begin(), nums.end(), target);
            
            vector<int> res; res.clear();
            if(*p1 != target) {
                res.push_back(-1);
                res.push_back(-1);
                return res;
            }
            
            res.push_back(p1 - nums.begin());
            res.push_back(p2 - nums.begin() - 1);
            
            return res;
        }
    };
    View Code
  • 相关阅读:
    intelliJ IDEA最常用的快捷键
    Git使用说明
    mac快速安装程序
    java面试-String、StringBuffer和StringBuilder的区别
    linux静态与动态库创建及使用实例
    linux下动态库编译的依赖问题
    动态库与静态库的区别
    gcc-4.8.3安装,gdb-7.6安装
    设计模式之单件模式
    设计模式之抽象工厂模式
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5096959.html
Copyright © 2011-2022 走看看