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

 

本题 明显的是在字符串中进行二分查找 只是不是简单的查找到目标数字target 而是找到他的左右端点

普通的二分查找中 在left right之间的mid处的数据与target做比较  小于则left右移 大于则right左移 直至等于找到或者left已经大于right未找到

本题中 自然可以按照上述方法找到target的位置 但并不能找到其左右端点  但是不管是否等于target 而左右继续移动 left和right 就可以找到其左右端点处了

1、二分查找中  mid处的数据<target left右移   其他情况 包括mid处数据=target right都左移  则最后的left即为左端点

2、与1相对   mid处数据>target  right左移 其他都left右移 则最后的right即为右端点

按照以上两步 即可以通过两次二分查找找到其左右端点 时间复杂度在O(lgn)里

 

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

 

此外 也可以一次普通的二分查找找到目标数据的位置后  在其左二分查找到左端点 其右二分查找到其右端点

这样的话总共三次二分查找  但是后两次的查找范围明显变小

posted @ 2017-02-16 17:09  糯米米一粒  阅读(138)  评论(0编辑  收藏  举报