forked from iamshubhamg/Leet-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedian of Two Sorted Arrays.cpp
52 lines (44 loc) · 1.02 KB
/
Median of Two Sorted Arrays.cpp
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
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> med;
double res;
int n=nums1.size();
int m=nums2.size();
int i=0;
int j=0;
while(i<n && j<m)
{
if(nums1[i]>=nums2[j])
{
med.push_back(nums2[j]);
j++;
}
else
{
med.push_back(nums1[i]);
i++;
}
}
while(i<n)
{
med.push_back(nums1[i]);
i++;
}
while(j<m)
{
med.push_back(nums2[j]);
j++;
}
int p=med.size();
if(p%2!=0)
{
res=med[p/2];
}
else if(p%2==0)
{ p--;
double x=med[p/2];
int z=(p/2)+1;
double y=med[z];
res=(x+y)/2;
}
return res;
}