Leetcode 4 Median of Two Sorted Arrays Java

来源:互联网 发布:高校法学教学软件 编辑:程序博客网 时间:2024/06/01 11:18

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

这道题目看似比较简单,做起来才发现暗藏玄机。。。。

这道题的一种思路,将题目转换为寻找第k小的值的问题。
程序如下:

            public double findMedianSortedArrays(int A[], int B[]) {                  int m = A.length;                  int n = B.length;                  int total = m+n;                  if ((total&1) == 1)                      return findKth(A, 0, m, B, 0, n, total/2+1);                  else              return (findKth(A, 0, m, B, 0, n, total/2) + findKth(A, 0, m, B, 0, n, total/2+1))/2;              }      public double findKth(int a[], int startA, int m, int b[], int startB, int n, int k)          {              if (m > n) return findKth(b, startB, n, a, startA, m, k);              if (m == 0)                   return b[startB + k-1];              if (k == 1)                   return min(a[startA], b[startB]);              int pa = min(k/2, m), pb = k - pa;              if (a[startA + pa-1] < b[startB + pb-1])                   return findKth(a, startA + pa, m-pa, b, startB, n, k - pa);              else                   return findKth(a, startA, m, b, startB + pb, n-pb, k-pb);          }              private int min(int a, int b){                  return a > b ? b : a;              }  
0 0