Accepted Ruby Solution


  • 0
    S
    def get_median(data)
      size = data.size
      if size.even?
        m = data[(size-1)/2]
        n = data[size/2]
        return (m+n)/2
      else
        return data[size/2]
      end
    end
    
    def find_median_sorted_arrays(nums1, nums2)
      n1 = nums1.size
      n2 = nums2.size
    
      if n1 > n2
        long = nums1
        short = nums2
      else
        long = nums2
        short = nums1
      end
    
      long_index = short_index = 0
      while short_index < short.size do
        value = short[short_index]
        insertion_position = find_pos_to_insert(long, value)
        long = insert(long, insertion_position, value)
        short_index += 1
      end
      get_median(long)
    end
    
    def insert(arr, position, value)
      start = position
      finish = arr.size - 1
      while finish >= start do
        arr[finish+1] = arr[finish]
        finish = finish - 1
      end
      arr[position] = value
      arr
    end
    
    def find_pos_to_insert(arr, value)
      start = 0
      finish = arr.size - 1
      while start <= finish do
        mid = (start + finish) / 2
        if value > arr[finish]
          return finish + 1
        elsif value < arr[start]
          return start - 1
        elsif value < arr[mid]
          finish = mid - 1
        elsif value > arr[mid]
          start = mid + 1
        else
          p "equal?"
        end
      end
    end
    

Log in to reply
 

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