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

    Given an array of integers sorted in ascending order, 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].

    直接用lower_bound()来二分大于等于它的位置,用upper_bound()来二分大于它的位置。

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            if(nums.size() == 0)
                return vector<int>{-1, -1};
                
            int x = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
            int y = upper_bound(nums.begin(), nums.end(), target) - nums.begin();
            if(x == nums.size() || nums[x] != target)
                return vector<int>{-1, -1};
            return vector<int>{x, y-1};
        }
    };
    
  • 相关阅读:
    第四周作业
    第三周作业
    第二周作业
    7-1,求最大值及下标值
    7-1.查找整数
    打印沙漏
    赚了还是亏了
    秋末学期总结
    机器学习小知识
    python 小知识
  • 原文地址:https://www.cnblogs.com/aiterator/p/6592095.html
Copyright © 2011-2022 走看看