Simple and easy to understand Java O(m+n) solution


  • 0
    S
        // Class that represents two sorted arrays like one merged sorted array
        private static class MergedArrayIterator {
            int[] nums1;
            int[] nums2;
            int index1 = 0;
            int index2 = 0;
            
            // Gets next element
            int getNext() {
                if (index1 >= nums1.length) { // first array end reached
                    return nums2[index2++]; // take next element from second
                }
    
                if (index2 >= nums2.length) { // second array end reached
                    return nums1[index1++]; // take next element from first
                }
    
                if (nums1[index1] < nums2[index2]) { // first array next element is smaller than second
                    return nums1[index1++]; // take next element from first
                }
    
                return nums2[index2++]; // take next element from second
            }
        }
        
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int total = nums1.length + nums2.length;        
            int m1 = (total - 1) / 2; // index of median element or one to the left
    
            MergedArrayIterator it = new MergedArrayIterator();
            it.nums1 = nums1;
            it.nums2 = nums2;
    
            // Just iterate for m1 times
            int m1v = it.getNext();
            
            for (int i = 0; i < m1; ++i) {
                m1v = it.getNext();
            }
            
            if (total % 2 == 0) { // if there are even number of elements, find mean            
                int m2v = it.getNext();
                return (m1v + m2v) / 2.0;
            } else {
                return m1v;
            }
           
        }
    

Log in to reply
 

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