O(m + n):
Note:
return rec[1] not rec[0].
1 class Solution { 2 public: 3 double findMedianSortedArrays(int A[], int m, int B[], int n) { 4 int mid = (m+n)/2 + 1, i = 0, j = 0; 5 vector<int> rec(2); 6 while (i + j < mid) { 7 int tmp1 = INT_MAX, tmp2 = INT_MAX; 8 rec[0] = rec[1]; 9 if (i < m) { 10 tmp1 = A[i]; 11 } 12 if (j < n) { 13 tmp2 = B[j]; 14 } 15 if (tmp1 < tmp2) { 16 rec[1] = tmp1; 17 i++; 18 } else { 19 rec[1] = tmp2; 20 j++; 21 } 22 } 23 if ((m+n)%2 =
1 class Solution { 2 public: 3 double findK(int A[], int m, int B[], int n, int k) { 4 if (m > n) { 5 return findK(B, n, A, m, k); 6 } 7 if (m == 0) { 8 return B[k-1]; 9 } 10 if (k == 1) { 11 return min(A[0], B[0]); 12 } 13 int ia = min(m, k/2), ib = k - ia; 14 if (A[ia-1] < B[ib-1]) { 15 return findK(A+ia, m-ia, B, n, k-ia); 16 } else if (A[ia-1] > B[ib-1]) { 17 return findK(A, m, B+ib, n-ib, k-ib); 18 } 19 return A[ia-1]; 20 } 21 double findMedianSortedArrays(int A[], int m, int B[], int n) { 22 if ((m + n)%2 == 1) { 23 return findK(A, m, B, n, (m+n)/2+1); 24 } 25 return (findK(A, m, B, n, (m+n)/2+1) + findK(A, m, B, n, (m+n)/2))/2; 26 } 27 };
= 1) return double(rec[1]); 24 return double(rec[0]+ rec[1])/2; 25 } 26 };
O(lg(m+n))
Note:
When do the comparison of A[ia-1] and B[ib-1], do not forget to return it.
时间: 2024-10-12 21:59:52