美文网首页
34. Search for a Range

34. Search for a Range

作者: Al73r | 来源:发表于2017-09-30 15:08 被阅读0次

题目

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

分析

在有序数组中查找目标存在的范围,直接用STL中的lower_bound()和upper_bound()两个函数撸两下就过了。

实现一

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        auto p1=lower_bound(nums.begin(), nums.end(), target);
        if(p1==nums.end() || *p1!=target) return {-1, -1};
        auto p2=upper_bound(nums.begin(), nums.end(), target);
        return {p1-nums.begin(), p2-nums.begin()-1};
    }
};

思考一

感觉这样太简单了,这题应该主要就是考察对于二分查找的理解,所以决定再手撸一遍二分查找。

实现二

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if(nums.empty()) return {-1, -1};
        int start=0, end=nums.size()-1;
        while(start<end){
            int mid = (start + end) / 2;
            if(nums[mid]>=target)
                end = mid;
            else
                start = mid+1;
        }
        if(nums[start]!=target) return {-1, -1};
        int a=start;
        start=0, end=nums.size()-1;
        while(start<end){
            int mid = (start + end) / 2;
            if(nums[mid]>=target+1)
                end = mid;
            else
                start = mid+1;
        }
        if(nums[start]==target) return {a, start};
        return {a, start-1};
    }
};

思考二

手撸成功,完成了上一题中所要做的改进,排名也有所提升。

相关文章

网友评论

      本文标题:34. Search for a Range

      本文链接:https://www.haomeiwen.com/subject/glogextx.html