Easy understang C++ solution 12 ms,how to be more fast?


  • 0
    1
        class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int l=0,r=nums.size()-1;
            int m=(l+r)/2;
            while(!(nums[m]==target&&(m==0||nums[m-1]!=target))&&l<r)
            {
                if(nums[m]<target) 
                {
                    if(m==l) l++;
                    else l=m;
                }
                else r=m;
                m=(l+r)/2;
            } 
            if(nums[m]!=target) return {-1,-1};
            int l0=m,r0=nums.size()-1;
            int m0=(l0+r0+1)/2;
            while(!(nums[m0]==target&&(m0==nums.size()-1||nums[m0+1]!=target))&&l0<r0)
            {
                if(nums[m0]<=target) l0=m0;
                else
                {
                    if(r0==m0) r0--;
                    else r0=m0;
                }
                m0=(l0+r0+1)/2;
            }
            return {m,m0};
        }
    };

Log in to reply
 

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