4. Median of Two Sorted Arrays

My Solution

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
43
44
45
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;

int p1 = 0;
int p2 = 0;

int last = 0;
int last_next = 0;
double median = 0;

if ((m + n) % 2 != 0) {
while(p1 + p2 < (m + n + 1) / 2){
if (p1 < m && (p2 >= n || nums1[p1] < nums2[p2])) {
last = nums1[p1];
p1++;
} else {
last = nums2[p2];
p2++;
}
}
median = last;
} else {
while(p1 + p2 < (m + n) / 2){
if (p1 < m && (p2 >= n || nums1[p1] < nums2[p2])) {
last = nums1[p1];
p1++;
} else {
last = nums2[p2];
p2++;
}
}
if (p1 < m && (p2 >= n || nums1[p1] < nums2[p2])) {
last_next = nums1[p1];
} else {
last_next = nums2[p2];
}

median = (last + last_next) / 2.0;
}

return median;
}
}

Remarks:

  1. check the border of arrays! p1 < m && (p2 >= n || nums1[p1] < nums2[p2])
  2. Use double but not float
  3. be careful of division results: /2.0 -> double; /2 -> integer
  4. TC $O(m+n)$

Binary Search, Recursive

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
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// Ensure nums1 is the smaller array
if (nums1.length > nums2.length) {
return findMedianSortedArrays(nums2, nums1);
}

int m = nums1.length;
int n = nums2.length;
int low = 0, high = m;

while (low <= high) {
int partitionX = (low + high) / 2;
int partitionY = (m + n + 1) / 2 - partitionX;

// Edge cases where partition is at the boundaries
int maxLeftX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];
int minRightX = (partitionX == m) ? Integer.MAX_VALUE : nums1[partitionX];

int maxLeftY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];
int minRightY = (partitionY == n) ? Integer.MAX_VALUE : nums2[partitionY];

// Check for correct partition
if (maxLeftX <= minRightY && maxLeftY <= minRightX) {
// If total length is even
if ((m + n) % 2 == 0) {
return (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2.0;
} else {
return Math.max(maxLeftX, maxLeftY);
}
} else if (maxLeftX > minRightY) {
high = partitionX - 1;
} else {
low = partitionX + 1;
}
}

throw new IllegalArgumentException("Input arrays are not sorted properly.");
}
}