median of two sorted arrays – leetcode a4

Problem

Problem description

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Analysis

  • Binary Search
  • K-th elements in two sorted arrays

Python Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class :
def get_k_th(self, a, b, n, m, k):
if (n <= 0): return b[k-1]
if (m <= 0): return a[k-1]
if (k == 1): return min(a[0], b[0])
if (b[m // 2] >= a[n // 2]):
if n//2 + m // 2 + 2 > k:
return self.get_k_th(a, b, n, m//2, k)
else:
return self.get_k_th(a[n//2+1:], b, n - (n//2+1), m, k - (n // 2 + 1))
else:
if n//2 + m // 2 + 2 > k:
return self.get_k_th(a, b, n//2, m, k)
else:
return self.get_k_th(a, b[m//2+1:], n, m - (m//2+1), k - (m // 2 + 1))
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
n = len(nums1)
m = len(nums2)
if (n + m) % 2 == 0:
return (self.get_k_th(nums1, nums2, n, m, (n+m)//2) + self.get_k_th(nums1, nums2, n, m, (n+m)//2 +1)) / 2
else:
return self.get_k_th(nums1, nums2, n, m, (n+m)//2+1)