Wednesday, April 9, 2014

Median of Two Sorted Arrays @LeetCode

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)).
package leetcode;
/**
* Solution: need some reasoning. This problem is extend to find kth number of two Sorted Array.
* Just copy other's solution, I didn't understand this problems. Will update later.
*
*
* Reference: http://fisherlei.blogspot.com/2012/12/leetcode-median-of-two-sorted-arrays.html
*
* @author jeffwan
* @date Apr 9, 2014
*/
public class FindMedianSortedArrays {
public double findMedianSortedArrays(int A[], int B[]) {
int len = A.length + B.length;
if (len % 2 == 0) {
return (findKth(A, 0, B, 0, len / 2) + findKth(A, 0, B, 0, len / 2 + 1)) / 2.0 ;
} else {
return findKth(A, 0, B, 0, len / 2 + 1);
}
}
// find kth number of two sorted array
public int findKth(int[] A, int A_start, int[] B, int B_start, int k){
// System.out.println("A_start: "+A_start+" B_start: "+B_start+" k: "+k);
if(A_start >= A.length)
return B[B_start + k - 1];
if(B_start >= B.length)
return A[A_start + k - 1];
if (k == 1)
return Math.min(A[A_start], B[B_start]);
int A_key = A_start + k / 2 - 1 < A.length
? A[A_start + k / 2 - 1]
: Integer.MAX_VALUE;
int B_key = B_start + k / 2 - 1 < B.length
? B[B_start + k / 2 - 1]
: Integer.MAX_VALUE;
if (A_key < B_key) {
return findKth(A, A_start + k / 2, B, B_start, k - k / 2);
} else {
return findKth(A, A_start, B, B_start + k / 2, k - k / 2);
}
}
// O(n) doesn't meet need of Problem
public double findMedianSortedArrays2(int A[], int B[]) {
int[] C = new int[A.length + B.length];
int i = 0;
int j = 0;
int index = 0;
while (i < A.length && j < B.length) {
if (A[i] < B[j]) {
C[index] = A[i];
i++;
} else {
C[index] = B[j];
j++;
}
index++;
}
while (i < A.length) {
C[index] = A[i];
i++;
index++;
}
while (j < B.length) {
C[index] = B[j];
j++;
index++;
}
// Caculate median
int start, end, mid;
start = 0;
end = C.length - 1;
mid = start + (end - start) / 2;
if (C.length % 2 == 1) {
return C[mid];
} else {
return (double) (C[mid] + C[mid + 1]) / 2;
}
}
}

No comments:

Post a Comment