[LintCode/LeetCode] Median of two Sorted Arrays

NO IMAGE

Problem

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays.

Example

Given A=[1,2,3,4,5,6]

Naive method: O(m n) time

public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n1 = nums1.length, n2 = nums2.length;
int len = n1 n2;
if (len%2 == 0) return (find(nums1, nums2, len/2) find(nums1, nums2, len/2 1))/2.0;
else return (double)find(nums1, nums2, len/2 1);
}
public int find(int[] A, int[] B, int k) {
int res = 0;
int i = 0, j = 0;
while (k != 0 && i < A.length && j < B.length) {
if (A[i] < B[j]) res = A[i  ];
else res = B[j  ];
k--;
}
if (k != 0) {
if (i < A.length) res = A[i k-1];
else res = B[j k-1];
}
return res;
}
}