C++ AC implementation


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

Log in to reply
 

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