-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedian_Of_Two_Sorted_Arrays.h
70 lines (61 loc) · 1.18 KB
/
Median_Of_Two_Sorted_Arrays.h
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
#include <iostream>
#include <vector>
using namespace std;
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
int m = nums2.size();
int *arr = new int [m + n];
int i(0),j(0);
bool a1_end(0),a2_end(0);
int half_size = ((m + n) / 2) + 1;
int x(0);
for (; x < half_size; x++)
{
if(i == n)
{
a1_end = true;
break;
}
if(j == m)
{
a2_end = true;
break;
}
if(nums1[i] < nums2[j])
{
arr[x] = nums1[i];
nums1[i];
i++;
}
else
{
arr[x] = nums2[j];
nums2[j];
j++;
}
}
if(a1_end)
{
for(; j < m && j < half_size; j++)
{
arr[x] = nums2[j];
x++;
}
}
else if(a2_end)
{
for(; i < n && i < half_size; i++)
{
arr[x] = nums1[i];
x++;
}
}
if((m + n) % 2 == 0)
{
return ((arr[(m + n) / 2] + arr[((m + n) / 2) - 1]) / 2.0);
}
else
{
return arr[(m + n) / 2];
}
}