34. Search for a Range 查找一个区间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/llz62378/article/details/79124278

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

思路: 利用二分查找,寻找左边的边界和右边边界。

class Solution {
public:
    int LeftBound(vector<int> &nums, int target)
    {
        int begin = 0;
        int end = nums.size() - 1;
        
        // 要有等于:可能是begin和end都指向同一个target位置,也可能指向非值为target的位置
        while(begin <= end)
        {
            int mid = (begin + end) / 2;
            if(target == nums[mid])
            {
                if(mid == 0 || target > nums[mid - 1])
                    return mid;
                end = mid - 1;
            }
            else if(target > nums[mid])
            {
                begin = mid + 1;
            }
            else
            {
                end = mid - 1;
            }
        }
        return -1;
    }
    
    int RightBound(vector<int> &nums, int target)
    {
        int begin = 0;
        int end = nums.size() - 1;
        
        while(begin <= end)
        {
            int mid = (begin + end) / 2;
            if(target == nums[mid])
            {
                if(mid == nums.size() - 1 || target < nums[mid + 1])
                    return mid;
                begin = mid + 1;
            }
            else if(target > nums[mid])
            {
                begin = mid + 1;
            }
            else
            {
                end = mid - 1;
            }
        }
        return -1;
    }
    
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> v;
        v.push_back(LeftBound(nums, target));
        v.push_back(RightBound(nums, target));
        return v;
    }
};


猜你喜欢

转载自blog.csdn.net/llz62378/article/details/79124278