-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4. Median of Two Sorted Arrays
32 lines (27 loc) · 1.1 KB
/
4. Median of Two Sorted Arrays
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
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// Get the sizes of both input arrays.
int n = nums1.length;
int m = nums2.length;
// Merge the arrays into a single sorted array.
int[] merged = new int[n + m];
int k = 0;
for (int i = 0; i < n; i++) {
merged[k++] = nums1[i];
}
for (int i = 0; i < m; i++) {
merged[k++] = nums2[i];
}
// Sort the merged array.
Arrays.sort(merged);
// Calculate the total number of elements in the merged array.
int total = merged.length;
if (total % 2 == 1) {
// If the total number of elements is odd, return the middle element as the median.
return (double) merged[total / 2];
} else {
// If the total number of elements is even, calculate the average of the two middle elements as the median.
int middle1 = merged[total / 2 - 1];
int middle2 = merged[total / 2];
return ((double) middle1 + (double) middle2) / 2.0;
}