地址:http://oj.leetcode.com/problems/median-of-two-sorted-arrays/
There are two sorted arrays A and B 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)).
思路:这题参考了github上一份代码,注意时间复杂度要求是O(log (m+n)),看到这个应该联想到是系统递归的栈消耗。
find_kth_num(第K小数)使用于在两个array里找到第K小的数,不仅仅是中值。
另外注意k和下标索引差1.
这道题刚开始做比较难理解,需要多揣摩。
c++ 参考代码;
class Solution {
public:
//find kth smallest number, which applies to any kth number
double find_kth_num(int A[], int m, int B[], int n, int k)
{
if(m > n)
return find_kth_num(B, n, A, m, k);
if(m==0)
return B[k-1];
if(k == 1)
return min(A[0], B[0]);
int idx_a = min(m, k/2);
int idx_b = k - idx_a;
if(A[idx_a-1] < B[idx_b-1])
return find_kth_num(A+idx_a, m-idx_a, B, n, k-idx_a);
else if(A[idx_a-1] > B[idx_b-1])
return find_kth_num(A, m, B+idx_b, n-idx_b, k-idx_b);
else
//these two parts together count to lenght k, just find the kth smallest number
return A[idx_a-1];
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
if((m+n)&1)
return (double)find_kth_num(A, m, B, n, (m+n)/2+1);
else
return 0.5 * (find_kth_num(A, m, B, n, (m+n)/2) + find_kth_num(A, m, B, n, (m+n)/2+1));
}
};
python 参考代码:
class Solution:
# @return a float
def find_kth_num(self, A, m, B, n, k):
if m > n:
return self.find_kth_num(B, n, A, m, k)
if not A:
return float(B[k-1])
if k == 1:
return float(min(A[0], B[0]))
idx_a = min(m, k//2)
idx_b = k - idx_a
if A[idx_a-1] < B[idx_b-1]:
return self.find_kth_num(A[idx_a:], m-idx_a, B, n, k-idx_a)
elif A[idx_a-1] > B[idx_b-1]:
return self.find_kth_num(A, m, B[idx_b:], n-idx_b, k-idx_b)
else:
return float(A[idx_a-1])
def findMedianSortedArrays(self, A, B):
if (len(A)+len(B)) & 0x1:
return self.find_kth_num(A, len(A), B, len(B), (len(A)+len(B)+1)//2)
else:
return (self.find_kth_num(A, len(A), B, len(B), (len(A)+len(B))//2) + self.find_kth_num(A, len(A), B, len(B), (len(A)+len(B))//2 + 1)) / 2.0
c++
Another trial, more simpler
class Solution {
private:
double find(int A[], int m, int B[], int n, int k) {
if(m > n)
return find(B, n, A, m, k);
if(!m)
return B[k-1];
if(k==1)
return min(A[0], B[0]);
int x = min(k/2, m);
if(A[x-1] < B[x-1])
return find(A+x, m-x, B, n, k-x);
else
return find(A, m, B+x, n-x, k-x);
}
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
if((m+n)%2)
return find(A, m, B, n, (m+n)/2+1);
else
return 0.5*(find(A, m, B, n, (m+n)/2) + find(A, m, B, n, (m+n)/2+1));
}
};