Repository navigation
Expand file tree
/
Copy pathMedianOfTwoSortedArrays.cs
More file actions
71 lines (66 loc) · 1.84 KB
/
Copy pathMedianOfTwoSortedArrays.cs
File metadata and controls
71 lines (66 loc) · 1.84 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
namespace Code.Sort;
public class MedianOfTwoSortedArrays
{
/// <param name="nums1"></param>
/// <param name="nums2"></param>
/// <returns>the median of the two sorted arrays</returns>
static public double Solution(int[] nums1, int[] nums2)
{
int m = nums1.Length;
int n = nums2.Length;
if (m > n)
{
return Solution(nums2, nums1);
}
int low = 0, high = m, halfLen = (m + n + 1) / 2;
while (low <= high)
{
int i = (low + high) / 2;
int j = halfLen - i;
if (i < high && nums2[j - 1] > nums1[i])
{
low = i + 1; // i is too small
}
else if (i > low && nums1[i - 1] > nums2[j])
{
high = i - 1; // i is too big
}
else
{ // i is perfect
int maxOfLeft;
if (i == 0)
{
maxOfLeft = nums2[j - 1];
}
else if (j == 0)
{
maxOfLeft = nums1[i - 1];
}
else
{
maxOfLeft = Math.Max(nums1[i - 1], nums2[j - 1]);
}
if ((m + n) % 2 == 1)
{
return maxOfLeft;
}
int minOfRight;
if (i == m)
{
minOfRight = nums2[j];
}
else if (j == n)
{
minOfRight = nums1[i];
}
else
{
minOfRight = Math.Min(nums1[i], nums2[j]);
}
return ((double)maxOfLeft + (double)minOfRight) / 2;
}
}
return 0;
}
}