-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortedArray.java
More file actions
44 lines (34 loc) · 898 Bytes
/
Copy pathMergeSortedArray.java
File metadata and controls
44 lines (34 loc) · 898 Bytes
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
class MergeSortedArray {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int i = 0, j = 0;
int pos = 0;
int[] result = new int[m + n];
while (i < m && j < n) {
if (nums1[i] < nums2[j]) {
result[pos] = nums1[i];
i++;
} else {
result[pos] = nums2[j];
j++;
}
pos++;
}
while (i < m) {
result[pos] = nums1[i];
i++;
pos++;
}
while (j < n) {
result[pos] = nums2[j];
j++;
pos++;
}
int total = m + n;
if (total % 2 == 1) {
return result[total / 2];
}
return (result[total / 2 - 1] + result[total / 2]) / 2.0;
}
}