Q4 Median of two sorted arrays
首先奉上题目:
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)).
Sol 1
看到题目是sorted arrays就觉得应该还挺简单的,按照朴素思想应该也能解出来,也即将两个arrays遍历一半,复杂度应为O(m+n2),但是题目要求复杂度是O(log(m+n)),因此需要改进一下
Sol2
根据以往的经验来说,log(m+n)的复杂度是采用类二分法进行比较。取一组数列的中间项a和另一组数列的中间项b进行比较,若a>b,则取array1的m4项和array2的m4+n2进行比较,以此类推。这个推理过程在leetcode的solution上面有十分详细的推导过程。
另外还有一个需要注意的关键点是,n+m为偶数时,中位数为两者的均值。