Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save codertcet111/8cc24487f99efdab2fed6f2458f5f043 to your computer and use it in GitHub Desktop.
Save codertcet111/8cc24487f99efdab2fed6f2458f5f043 to your computer and use it in GitHub Desktop.
Leetcode 4: Median of two sorted array
Leetcode 4: Median of two sorted array
# @param {Integer[]} nums1
# @param {Integer[]} nums2
# @return {Float}
def find_median_sorted_arrays(nums1, nums2)
res=[]
a, b, i = 0, 0, 0
sum_m_n = nums1.count + nums2.count
if sum_m_n%2 == 0 #even
until_i = sum_m_n/2
while i <= until_i do
if nums1[a] == nil
res << nums2[b]
b = b + 1
elsif nums2[b] == nil
res << nums1[a]
a = a + 1
elsif nums1[a] <= nums2[b]
res << nums1[a]
a = a + 1
else
res << nums2[b]
b = b + 1
end
i = i + 1
end
return (res[-1] + res[-2])/2.0
else #odd
until_i = (sum_m_n - 1)/2
while i <= until_i do
if nums1[a] == nil
res << nums2[b]
b = b + 1
elsif nums2[b] == nil
res << nums1[a]
a = a + 1
elsif nums1[a] <= nums2[b]
res << nums1[a]
a = a + 1
else
res << nums2[b]
b = b + 1
end
i = i + 1
end
return res[-1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment