Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- We know the size of both the arrays so if we merge both the arrays and break the combined arrays in two half,then there will be some elements from array1 and some elements from array2.some can be zero also,But one thing for sure that each half will be (n1+n2)/2 lets think about even count now.
- for eg. arr1: [1,3,4,7,10,12] ->size=6
- arr2: [2,3,6,15] ->size=4
- so total size of combined array=10,size of each half=10/2=5
- so let's assume 3 element from first array in first half,then only 2 elements will be from
- second array in first half and if we have first half,then we can find maximum element from
- first half and minimum from second half for median.
- So,now basically the problem is divide the first array such that left side elements of the
- array must belong to the actual combined array first half.
- suppose if be take 2 elements from arr1 then first half of combined array will be 1,3 and
- 2,3,6
- eg. 1 3 | 4 6 10 12
- 2 3 6 | 15
- so last element of first partition of first array will always be smaller than the
- the first element of second half because they belong to same array.same for second array.
- but if 1 3 and 2 3 6 is actually the first half of combined array then 3 should also be smaller
- than 15 and 6 also should smaller than 4 becuase whatever in first array should be smaller than
- all elements of second array.If it happend we got the actual partition.
- We apply binary search for finding the actual cut1.
- */
- class Solution{
- public:
- double MedianOfArrays(vector<int>& arr1, vector<int>& arr2){
- if(arr1.size()>arr2.size()) return MedianOfArrays(arr2,arr1);
- int n1=arr1.size();
- int n2=arr2.size();
- int low=0,high=n1; //because cut1 will be in this range only,means elements till cut1 can contains
- //elements between 0 to n1
- while(low<=high){
- int cut1=(low+high)/2;
- int cut2=(n1+n2+1)/2-cut1;
- int left1,left2,right1,right2;
- if(cut1==0) left1=INT_MIN; else left1=arr1[cut1-1]; //If no elements from first array,then left1 should
- if(cut2==0) left2=INT_MIN; else left2=arr2[cut2-1]; //INT_MIN to satisfy condition and same for left2
- if(cut1==n1) right1=INT_MAX; else right1=arr1[cut1]; //If all elements from first arrat,then right1
- if(cut2==n2) right2=INT_MAX; else right2=arr2[cut2]; //should be INT_MAX to satisfy condition.
- if(left1<=right2 && left2<=right1){
- if((n1+n2)%2) return max(left1,left2); //Max because sometime left1 can have INT_MIN
- else return (max(left1,left2)+min(right1,right2))/2.0; //MIn for right1 and 2 because right1 can
- } //can have INT_MAX
- else if(left1>right2) high=cut1-1; //reduce the elements in first array
- else low=cut1+1; //increase the elements in first array.
- }
- return 0.0;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement