LeetCode - Algorithms - 4. Median of Two Sorted Arrays

Problem

4. Median of Two Sorted Arrays

Follow up

The overall run time complexity should be O(log (m+n)).

Java

extra space

On the basis of 88. Merge Sorted Array, this is not preferable method, just better than nothing.

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
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
final int m = nums1.length;
final int n = nums2.length;
if (m == 0)
return (n & 1) == 1 ? nums2[n / 2] : (nums2[n / 2 - 1] + nums2[n / 2]) / 2.0;
if (n == 0)
return (m & 1) == 1 ? nums1[m / 2] : (nums1[m / 2 - 1] + nums1[m / 2]) / 2.0;
int[] aux = merge(nums1, m, nums2, n);
double median = ((m + n) & 1) == 1 ? aux[(m + n) / 2] : (aux[(m + n) / 2 - 1] + aux[(m + n) / 2]) / 2.0;
return median;
}

private int[] merge(int[] nums1, int m, int[] nums2, int n) {
int[] aux = new int[m + n];
if (m == 0) {
for (int i = 0; i < n; i++)
aux[i] = nums2[i];
return aux;
} else {
for (int i = 0; i < m; i++)
aux[i] = nums1[i];
}
int idx = m + n - 1;
m--;
n--;
for (; m >= 0 && n >= 0; ) {
if (nums1[m] < nums2[n]) {
aux[idx--] = nums2[n];
n--;
} else {
aux[idx--] = nums1[m];
m--;
}
}
if (n >= 0) {
for (int i = 0; i <= n; i++)
aux[i] = nums2[i];
}
return aux;
}
}

Submission Detail

  • 2091 / 2091 test cases passed.
  • Runtime: 2 ms, faster than 99.73% of Java online submissions for Median of Two Sorted Arrays.
  • Memory Usage: 40.1 MB, less than 10.39% of Java online submissions for Median of Two Sorted Arrays.