There are two sorted arrays nums1
and nums2
of size n
and m
respectively. Find the median of the two sorted arrays. You may assume nums1
and nums2
cannot both be empty.
nums1 = [1, 3] nums2 = [2] The median is 2.0
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
Since both input arrays are already sorted, a naive solution would be to merge the arrays by iterating through each and inserting the items into a new array. Then calculate the median.
initialize i and j to 0
initialize length of new array to the sum of the length the input arrays
initialize an empty array
while i is less then length of nums1 or j is less than length of nums2
if all elements from nums1 have been merged
merge element nums2[j]
increment j
else if all elements from nums2 have been merged
merge element nums1[i]
increment i
else
if element nums1[i] <= element nums2[j]
merge element nums1[i]
increment i
else
merge element nums2[j]
increment j
find midpoint (length / 2)
if length is even
return the average of merged_array[mid] and merged_array[mid - 1]
else
return merged_array[mid]
#programming #leetcode #rustlang #rust #algorithms