C++ solution,easy to understand,using binary search


  • 2
    Q
    /*
     *  http://www.skysq.com
     *  by  sky无限
     *  skyqsk@126.com
     */
    
     class Solution {
     public:
      vector<int> searchRange(vector<int>& nums, int target) {
        vector<int>t;
        int ans=-1;
        int l,r,a;
        ans=bsearch(nums,target,0,nums.size()-1);
        if(ans==-1)
        {
            return vector<int>{-1,-1};
        }
        a=ans;
        while((l=bsearch(nums,target,0,ans-1))!=-1)
              ans=l;
        t.push_back(ans);
        ans=a;
        while((r=bsearch(nums,target,ans+1,nums.size()-1))!=-1)
           ans=r;
        t.push_back(ans);
        return t;
    }
    
    int bsearch(vector<int>& nums,int target,int start,int end)
    {
        int mid;
        while(start<=end)
        {
            mid=(start+end)/2;
            if(nums[mid]==target)
            {
                return mid;
            }
            else if(nums[mid]>target)
               end=mid-1;
            else
               start=mid+1;
        }
        return -1;
       }
    };

Log in to reply
 

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