Skip to content

added Median_of_two_sorted_arrays.cpp #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 9, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Median_of_two_sorted_arrays.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution {
public:
double find(vector<int>& nums1, vector<int>& nums2)
{
int n = nums1.size(),m = nums2.size();

int l = 0,h = n;
while(l<=h)
{
int part1= (l+h)/2;
int part2=(n+m+1)/2 - part1;

int l1=(part1==0)? INT_MIN: nums1[part1-1];
int r1= (part1==n)? INT_MAX: nums1[part1];
int l2=(part2==0)? INT_MIN: nums2[part2-1];
int r2= (part2==m)? INT_MAX: nums2[part2];

if(l1<=r2 && l2<=r1)
{
if((n+m)%2)
return (double)max(l1,l2);
else
{
return (double)(max(l1,l2)+ min(r1,r2))/2.0;
}
}

else if(l1>r2)
h=part1-1;
else
l=part1+1;
}
return 0;
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n=nums1.size(),m=nums2.size();
if(n>m)return find(nums2,nums1);
else return find(nums1,nums2);

}

};