generated from projeto-de-algoritmos-2024/RepositorioTemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-Median-of-Two-Sorted-Arrays.cs
44 lines (39 loc) · 1.25 KB
/
4-Median-of-Two-Sorted-Arrays.cs
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
public class Solution {
private static void Merge(int[] array, int[] left, int[] right)
{
int i = 0, j = 0, k = 0;
// Mescla enquanto houver elementos em ambos os subarrays
while (i < left.Length && j < right.Length)
{
if (left[i] <= right[j])
{
array[k++] = left[i++];
}
else
{
array[k++] = right[j++];
}
}
// Copia os elementos restantes do subarray esquerdo (se houver)
while (i < left.Length)
{
array[k++] = left[i++];
}
// Copia os elementos restantes do subarray direito (se houver)
while (j < right.Length)
{
array[k++] = right[j++];
}
}
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
int[] mergedArray = new int[nums1.Length + nums2.Length];
Merge(mergedArray, nums1, nums2);
double m;
if (mergedArray.Length % 2 == 0){
m = (mergedArray[mergedArray.Length / 2] + mergedArray[(mergedArray.Length / 2) - 1]) / 2.0;
} else {
m = mergedArray[mergedArray.Length / 2];
}
return m;
}
}