一道二分
一道二分
Given two sorted arrays nums1
and nums2
of
size m
and n
respectively, return the
median of the two sorted arrays.
The overall run time complexity should be \(O(\log (m+n))\).
1 | typedef Comparable int; |
Solution
find the \(k\)th min number, where: \[ k = \begin{cases} \dfrac{m+n}{2},\ \text{when}\ m+n\ \text{is even},\\\\ \dfrac{m+n+1}{2},\ \text{when}\ m+n\ \text{is odd}. \end{cases} \] To find the number, compare \(A[k/2-1]\) and \(B[k/2-1]\):
- if \(A[k/2-1] \leq B[k/2-1]\), remove \(A[0:k/2-1]\),
- if \(A[k/2-1] > B[k/2-1]\), remove \(B[0:k/2-1]\).
and some cases:
- if \(A[k/2-1]\) or \(B[k/2-1]\) is out of bound, choose the last element of the array.
- if an array is empty, find the kth min number in the other.
- if \(k=1\), return \(\min(A[0], B[0])\)
1 | int getK(const vector<Comparable> &l1, const vector<Comparable> &l2, int k){ |