forked from garvit-bhardwaj/Leetcode-Problems-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedian_Of_Two_Sorted_Arrays
33 lines (33 loc) · 1022 Bytes
/
Median_Of_Two_Sorted_Arrays
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
class Solution {
public:
double mediann(vector<int>&a,vector<int>&b){
int m=a.size();
int n=b.size();
if(m>n)
return mediann(b,a);
int l=0,r=m;
while(l<=r){
int partx=l+(r-l)/2;
int party=(m+n+1)/2-partx;
int maxlx=(partx==0)?INT_MIN:a[partx-1];
int minrx=(partx==m)?INT_MAX:a[partx];
int maxly=(party==0)?INT_MIN:b[party-1];
int minry=(party==n)?INT_MAX:b[party];
if(maxlx<=minry&&maxly<=minrx){
if((m+n)%2==0)
return (double)(max(maxlx,maxly)+min(minrx,minry))/2;
else
return (double)(max(maxlx,maxly));
}else if(maxlx>minry)
r=partx-1;
else
l=partx+1;
}
return -1.0;
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
double ans;
ans=mediann(nums1,nums2);
return ans;
}
};