Share my cpp code


  • 0
    B
    class Solution 
    {
    public:
    vector<int> searchRange(vector<int>& nums, int target) 
    {
        vector<int> ret(2,-1);
        int l=0;
        int r=nums.size()-1;
        int mid;
        int got=-1;
        while(l<=r)
        {
            mid=(l+r)/2;
            if(nums[mid]>target){r=mid-1;}
            else if(nums[mid]<target){l=mid+1;}
            else {got=mid;break;}
        }
        if(got!=-1)
        {
           l=got;
           while(l>=0 && nums[l]==target)
           {l--;}
           ret[0]=l+1;
           r=got;
           while(r<=nums.size()-1 && nums[r]==target)
           {r++;}
           ret[1]=r-1;
        }
        return ret;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.