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)).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 |
double
findMedianSortedArrays( int
A[], int
m, int
B[], int
n) { if (m<3 || n<3) return
TrivialMedian(A,m,B,n); int
i = m/2; int
j = (m % 2 == 0 && n % 2 == 0) ? n/2-1 : n/2; if (A[i] >= B[j]){ if (j >= m-i-1) return
findMedianSortedArrays(A,i+1,B+m-i-1,n-m+i+1); else return
findMedianSortedArrays(A,m-j,B+j,n-j); } else { if (i <= n-j-1) return
findMedianSortedArrays(A+i,m-i,B,n-i); else return
findMedianSortedArrays(A+n-j-1,m-n+j+1,B,j+1); } } double
TrivialMedian( int
A[], int
m, int
B[], int
n){ vector< int > nums ; for ( int
i = 0; i < m; i++) nums.push_back(A[i]); for ( int
i = 0; i < n; i++) nums.push_back(B[i]); sort(nums.begin(),nums.end()); int
k = m+n; if (k % 2 == 0) return
0.5*(nums[k/2]+nums[k/2 - 1]); else return
nums[k/2]; } |
【题解】【数组】【Leetcode】Median of Two Sorted Arrays,布布扣,bubuko.com
【题解】【数组】【Leetcode】Median of Two Sorted Arrays
原文地址:http://www.cnblogs.com/wei-li/p/findMedianSortedArrays.html