C++ Solution using Merging


  • 0
    F
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {                     
            int nums1_len=nums1.size(), nums2_len=nums2.size();        
            if(nums1_len==1 && nums2_len==1) return (nums1[0]+ nums2[0])*1.0/2;        
            if(nums1_len==1 && nums2_len==0) return nums1[0]*1.0;       
            if(nums1_len==0 && nums2_len==1) return (nums2[0])*1.0;        
            int total_len=nums1_len+nums2_len;        
            int temp[nums1_len+nums2_len];        
            int index=0, count1=0, count2=0;        
            while(count1<nums1_len && count2<nums2_len){
                if(nums1[count1]<=nums2[count2]) temp[i++]=nums1[count1++];
                else temp[i++]=nums2[count2++];
            }
            while(count1<nums1_len)
                temp[i++]=nums1[count1++];
            while(count2<nums2_len)
                temp[i++]=nums2[count2++];
            double median;       
            median= total_len%2==1 ? temp[(int)total_len/2]: (temp[(int)total_len/2]+ temp[((int)total_len/2)-1])*1.0/2;        
            return median;
    	}
    

Log in to reply
 

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