34. Search for a Range

来源:互联网 发布:黑帽seo网页劫持 编辑:程序博客网 时间:2024/06/16 17:03

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

题目要求是在logn 的复杂度下完成。所以for循环一个个循环就不可能了,那么就必须要用二分查找,但是二分查找又有个问题,只能找到一个,由于给出的列表是升序排序的,所以要查到的相同数字只能在一起,所以我们用两次二分查找,第二次的二分查找的lo是在一次的查找过程的lo。

class Solution {public:    vector<int> searchRange(vector<int>& nums, int target) {        vector<int> res(2,-1);        if(nums.size()==0) return res;        int lo=0, hi = nums.size()-1;        while(lo<hi)        {            int mid = (lo+hi)/2;            if(nums[mid]<target)                lo = mid+1;            else                 hi=mid;        }        if(nums[lo]!=target) return res;        else res[0]=lo;        hi=nums.size()-1;        while(lo<hi)        {            int mid =1+ ((lo+hi)/2);            if(nums[mid]>target)                hi=mid-1;            else                 lo=mid;        }        res[1]=hi;        return res;    }};
原创粉丝点击