There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
https://www.youtube.com/watch?v=ScCg9v921ns
Tutorial in this link is very fantastic and I like this explanation in this video.
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> mergedArray = mergeTwoSortedArry(nums1,nums2);
int k = mergedArray.size();
int result;
if(mergedArray.size()%2 == 0)
{
result = (mergedArray[(k-1)/2] + mergedArray[k/2])/2;
return result;}else{
result = mergedArray[k/2];
}
return result;
}
vector<int> mergeTwoSortedArry(vector<int> nums1,vector<int> nums2){
vector<int> merge{};
int i =0, j=0, k=0;
while(i<nums1.size() && j<nums2.size()){
merge[k++] = nums1[i] < nums2[j]?nums1[i++]:nums2[j++];
}
while(i<nums1.size()){
merge[k++] = nums1[i++];
}
while(j<nums2.size()){
merge[k++] = nums2[j++];
}
return merge;
}
};
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 maxly=(party==0)?INT_MIN:b[party-1];
int minrx=(partx==m)?INT_MAX:a[partx];
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;
}
};
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int lenA = nums1.length,lenB = nums2.length;
if(lenA > lenB){return findMedianSortedArrays(nums2,nums1);}
if(lenA == 0){
return (nums2[(lenB-1)/2] + nums2[lenB/2])/2;
}
int len = lenA + lenB;
int A_start = 0,A_end = lenB;
int cutA,cutB;
while(A_start<=A_end){
cutA = A_start + (A_end-A_start)/2;
cutB = (len+1)/2-cutA;
double L1 = (cutA == 0)? Integer.MIN_VALUE:nums1[cutA-1];
double L2 = (cutA == 0)? Integer.MIN_VALUE:nums2[cutB-1];
double R1 = (cutA == lenA)? Integer.MAX_VALUE:nums1[cutA];
double R2 = (cutA == lenB)? Integer.MAX_VALUE:nums2[cutB];
if(L1 > R2){A_end = cutA - 1;}
else if(L2 > L1){A_start = cutA + 1;}
else{
if(len%2==0){
return (Math.max(L1,L2) + Math.min(R1,R2))/2;
}else{
return Math.max(L1,L2);
}
}
}
return -1;
}
}