C++, <20lines, 9ms


  • 0
    S
        vector<int> searchRange(vector<int>& nums, int target) {
            vector<int> ret = {-1, -1};
            int lo = 0, hi = nums.size(), mid=-1;
            while (lo < hi) {
                mid = (lo + hi) / 2;
                if (nums[mid] < target)
                    lo = mid + 1;
                else if (nums[mid] > target)
                    hi = mid;
                else
                    break;
            }
            if(nums[mid] == target){
                int k = mid-1;
                while(k>=0 && nums[k]==target)k--;
                if(k+1>=0 && nums[k+1]==target)ret[0]=k+1;
                k = mid+1;
                while(k<nums.size() && nums[k]==target)k++;
                if(k-1<nums.size() && nums[k-1]==target)ret[1]=k-1;
            }
            return ret;
        }
    

Log in to reply
 

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