Share my solution


  • 0
    S

    #include<algorithm>
    #include<iostream>
    class Solution {
    public:
    double findMedianSortedArrays(vector<int> nums1, vector<int> nums2) {
    int m11,m12,m21,m22;
    int size1=nums1.size(),size2=nums2.size();
    vector<int> num_emp;

       if(size1<=2){
           for(auto it=nums1.begin();it!=nums1.end();++it)
             nums2.push_back(*it);
          sort(nums2.begin(),nums2.end());
          size1=0;
          size2=nums2.size();
       }
       else
       if(size2<=2){
           for(auto it=nums2.begin();it!=nums2.end();++it)
             nums1.push_back(*it);
          sort(nums1.begin(),nums1.end());
          size2=0;
          size1=nums1.size();
       }
       
       if(size1%2==0){m11=size1/2-1;m12=m11+1;}
       else{m11=size1/2;m12=m11;}
       
       if(size2%2==0){m21=size2/2-1;m22=m21+1;}
       else{m21=size2/2;m22=m21;}
       
       if(size1==0){
           return 0.5*(nums2[m21]+nums2[m22]);
       }
       if(size2==0){
           return 0.5*(nums1[m11]+nums1[m12]);
       }
       
       if(nums1[m11]<nums2[m21]){
           while(m21>0 && nums1[m11]<nums2[m21]){m21--;}
       }
       else if(nums1[m11]>nums2[m21]){
           while(m11>0 && nums1[m11]>nums2[m21]){m11--;}
       }
       
       if(nums1[m12]>nums2[m22]){
           while(m22<size2-1 && nums1[m12]>nums2[m22]){m22++;}
       }
       else if(nums2[m22]>nums1[m12]){
           while(m12<size1-1 && nums2[m22]>nums1[m12]){m12++;}
       }
       
       cout<<"m11="<<m11<<" m12="<<m12<<" m21="<<m21<<" m22="<<m22<<'\n';
       
       int front_remove=m11+m21, back_remove=size1-1-m12+size2-1-m22;
       while(front_remove>back_remove){
           if(m11>0){m11--;}
           else{m21--;}
           front_remove=m11+m21;
       }
       while(front_remove<back_remove){
           if(m12<size1-1){m12++;}
           else{m22++;}
           back_remove=size1-1-m12+size2-1-m22;
       }
       vector<int> num1(nums1.begin()+m11,nums1.begin()+m12+1), num2(nums2.begin()+m21,nums2.begin()+m22+1);
       
      
       if(num1.size()<=3 && num2.size()<=3){
           for(auto it=num2.begin();it!=num2.end();it++)
            num1.push_back(*it);
           sort(num1.begin(),num1.end());
           return findMedianSortedArrays(num1,num_emp);
       }
       else{
           return findMedianSortedArrays(num1,num2);
       }
       
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.