-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedianOfTwoSortedArrays.cs
More file actions
50 lines (45 loc) · 1.19 KB
/
MedianOfTwoSortedArrays.cs
File metadata and controls
50 lines (45 loc) · 1.19 KB
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
46
47
48
49
50
namespace CodeChallenge
{
public class MedianOfTwoSortedArrays
{
public double FindMedianSortedArrays(int[] num1, int[] num2)
{
int m = num1.Length;
int n = num2.Length;
int[] mergedNumbers = new int[m + n];
int i = 0;
int j = 0;
int k = 0;
while (i < m && j < n)
{
if (num1[i] < num2[j])
{
mergedNumbers[k++] = num1[i++];
}
else
{
mergedNumbers[k++] = num2[j++];
}
}
while (i < m)
{
mergedNumbers[k++] = num1[i++];
}
while (j < n)
{
mergedNumbers[k++] = num2[j++];
}
int totalLength = m + n;
if (totalLength % 2 == 1)
{
return mergedNumbers[totalLength / 2];
}
else
{
int mid1 = totalLength / 2;
int mid2 = mid1 - 1;
return (mergedNumbers[mid1] + mergedNumbers[mid2]) / 2;
}
}
}
}