C# solution using two Binary searches - O(log(n))


  • 0
    M
    public int[] SearchRange(int[] nums, int k) {
                int[] res = new int[] { -1, -1 };
    
               if (nums == null || nums.Length == 0)
                   return res;
               res[0] = Binary(nums,0,nums.Length-1, k, 'F');
               if(res[0]!=-1)
                   res[1] = Binary(nums,res[0],nums.Length-1, k, 'L');
    
               return res;
           }
       
        public  int Binary(int[] nums,int s, int e, int k, char c)
           {
               int res = -1;
               while (s <= e)
               {
                   int mid = s + (e - s) / 2;
                   if (nums[mid] == k)
                   {
                       res = mid;
                       if (c == 'F')
                           e = mid - 1;
                       else
                           s = mid + 1;
                   }
                   else
                   {
                       if (nums[mid] > k)
                           e--;
                       else
                           s++;
                   }
               }
    
               return res;
           }
    

Log in to reply
 

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