public static double findMedian(int[] a, int[] b) { int[] merged = new int[a.length + b.length]; int i = 0; int j = 0; int k = 0; while(k < merged.length) { if(i < a.length && j < b.length) { if(a[i] <= b[j]) { merged[k] = a[i]; i++; } else { merged[k] = b[j]; j++; } k++; } else if (j == b.length) { for(int l = i; l < a.length; l++) { merged[k] = a[l]; k++; i++; } } else { for(int l = j; l < b.length; l++) { merged[k] = b[l]; k++; j++; } } } if(merged.length % 2 != 0) { return (double) merged[merged.length/2]; } else { return ((double) (merged[merged.length/2] + merged[merged.length/2 - 1]))/2; } }
Wednesday, January 29, 2014
Coding Exercises Round II: #3 in 8 days
Problem: There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment