[leetcode]median of two sorted arrays【寻找第k小的数问题】

来源:互联网 发布:revit 会不会出mac版本 编辑:程序博客网 时间:2024/05/17 08:38

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)).

题意:给两个数组,求出两个数组加起来的中位数。

分析:最简单的方法,定义一个数组,将两个数组合并,然后sort排序,(快排),复杂度为O(nlogn),超时。
还有一种方法,寻找第K小的数。在这个题目中,就是寻找第(m+n)/2个数。
假设k=(m+n)/2,方法是找到nums1中的第k/2-1个数和nums2的第k/2-1个数,比较他们的大小(<,>,=)
如果等于,那么第k小的数就是这两个数之一。
如果小于,那么第k小的数一定在nums2的下一部分。
如果大于,一定在nums1的下一部分。

另外还需要几个边界条件。

如果A或者B为空,则直接返回B[k-1]或者A[k-1];如果k为1,我们只需要返回A[0]和B[0]中的较小值;如果A[k/2-1]=B[k/2-1],返回其中一个;
double findKth(int a[], int m, int b[], int n, int k)  {      //always assume that m is equal or smaller than n      if (m > n)          return findKth(b, n, a, m, k);      if (m == 0)          return b[k - 1];      if (k == 1)          return min(a[0], b[0]);      //divide k into two parts      int pa = min(k / 2, m), pb = k - pa;      if (a[pa - 1] < b[pb - 1])          return findKth(a + pa, m - pa, b, n, k - pa);      else if (a[pa - 1] > b[pb - 1])          return findKth(a, m, b + pb, n - pb, k - pb);      else          return a[pa - 1];  }  class Solution  {  public:      double findMedianSortedArrays(int A[], int m, int B[], int n)      {          int total = m + n;          if (total & 0x1)              return findKth(A, m, B, n, total / 2 + 1);          else              return (findKth(A, m, B, n, total / 2)                      + findKth(A, m, B, n, total / 2 + 1)) / 2;      }  }; 

因为每次都有k/2个数被删除,所以时间复杂度为log(k),由于k=(m+n)/2,所以时间复杂度为log(m+n)。

0 0
原创粉丝点击