Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f908042

Browse files
authored
Create median
1 parent afd219d commit f908042

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

median

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution {
2+
public:
3+
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
4+
5+
int lenA=nums1.size();
6+
int lenB=nums2.size();
7+
int i,j;
8+
9+
if(lenA>lenB)
10+
{
11+
vector<int> temp;
12+
temp=nums1;
13+
nums1=nums2;
14+
nums2=temp;
15+
16+
}
17+
lenA=nums1.size();
18+
lenB=nums2.size();
19+
if(lenA==0)
20+
return -1;
21+
22+
int imin=0,imax=lenA;
23+
while(imin<=imax)
24+
{
25+
i=(imin+imax)/2;
26+
j=(lenA+lenB+1)/2-i;
27+
if(i<lenA&&nums2[j-1]>nums1[i])
28+
{
29+
imin=i+1;
30+
31+
}
32+
else if(i>0&&nums1[i-1]>nums2[j])
33+
{
34+
imax=i-1;
35+
36+
}
37+
else
38+
break;
39+
}
40+
int max_left,min_right;
41+
if(i==0) max_left=nums2[j-1];
42+
else if(j==0) max_left=nums1[i-1];
43+
else max_left=max(nums1[i-1],nums2[j-1]);
44+
45+
if((lenA+lenB)%2==1)
46+
{
47+
48+
return max_left;
49+
50+
}
51+
52+
53+
if(i==lenA) min_right=nums2[j];
54+
else if(j==lenB) min_right=nums1[i];
55+
else min_right=min(nums1[i],nums2[j]);
56+
57+
return (double(max_left+min_right)/2);
58+
59+
}
60+
};

0 commit comments

Comments
 (0)