Search for a Range

Given a sorted array of integers, 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].

描述:在一个给定的有序数组中查找一个目标在数组的起止位置。如果不存在则返回[0,0]

解决思路:

(1)二分查找是否存在target,不存在的话返回[0,0]

(2)存在的话以这个元素为中心,前后查询是否还有目标元素。

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

        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值