This is regarding Leetcode problem:
https://leetcode.com/problems/median-of-two-sorted-arrays/
My approach was to compare if number in nums1 is smaller than number in nums2, if yes then add it to a third list. Otherwise add nums2 number to that list, and increment counters accordingly. After that, i have a sorted list which in which it is easier to find median. Look at code below (got accepted in LeetCode):
nums_sorted = []
i,j = 0,0
while i<len(nums1) and j<len(nums2):
if nums1[i]<=nums2[j]:
nums_sorted.append(nums1[i])
i+=1
else:
nums_sorted.append(nums2[j])
j+=1
if i!=len(nums1):
while i<len(nums1):
nums_sorted.append(nums1[i])
i+=1
if j!=len(nums2):
while j<len(nums2):
nums_sorted.append(nums2[j])
j+=1
length = len(nums_sorted)
if length%2:
print("Odd numbers list: ", nums_sorted)
return float(nums_sorted[length//2])
else:
print("Even numbers list: ", nums_sorted)
return (nums_sorted[length//2 -1] + nums_sorted[length//2])/2Is it a horrible approach? Isn't it O(n+m) ? Other complex solutions are driving me crazy