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].

    如果不要求实现,用c++stl的lower_bound和upper_bound就可以了

    class Solution {
    public:
        int lower_bound(vector<int>& nums,int numsSize,int target)
        {
            int low = 0,high = numsSize;
            while(low<high){
                int mid = low+(high-low)/2;
                if(target <= nums[mid]){
                    high = mid;
                }else{
                    low = mid+1;
                }
            }
            return low;
        }
        int upper_bound(vector<int>& nums,int numsSize,int target)
        {
            int low = 0,high = numsSize;
            while(low<high){
                int mid = low+(high-low)/2;
                if(target < nums[mid]){
                    high = mid;
                }else{
                    low = mid+1;
                }
            }
            return low;
        }
        vector<int> searchRange(vector<int>& nums, int target) {
            int numsSize = nums.size();
            int low = lower_bound(nums,numsSize,target);
            vector<int> res;
            if(nums[low]!=target){
                res.push_back(-1);
                res.push_back(-1);
            }else{
                int high = upper_bound(nums,numsSize,target);
                res.push_back(low);
                res.push_back(high-1);
            }
            return res;
        }
    };
  • 相关阅读:
    排序算法整理
    V-REP Plugin 开发
    YAML-CPP
    YAML
    V-REP Remote API
    V-REP Plugin
    结构化方法与面向对象方法的比较
    敏捷软件开发vs传统软件工程
    个人项目-地铁出行路线规划程序
    Week1个人作业
  • 原文地址:https://www.cnblogs.com/zengzy/p/5002399.html
Copyright © 2011-2022 走看看