Clean Iterative Java Solution


  • -1
    J

    I didn't merge declarations for clarity's sake. I always assume you need to check for empty arrays, but it's nice to be able to ignore those cases since they don't really add much to the problem solving. I originally just made a half-length array and filled it as I went, but there is no need to keep anything but the last two values in memory so I went with the lead/trailing value strategy.

    public class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int runningIndex = 0;
            int len1 = nums1.length;
            int len2 = nums2.length;
            int totalLength = len1 + len2;
            int runningIndexLimit = (totalLength/2)+1;
            int index1 = 0;
            int index2 = 0;
            int leadVal = 0;
            int trailingVal = 0;
            
            while (runningIndex < runningIndexLimit) {
                trailingVal = leadVal;
                
                if(index1 > len1-1) {
                    leadVal = nums2[index2++];
                } else if(index2 > len2-1) {
                    leadVal = nums1[index1++];
                } else {
                    if (nums1[index1] == nums2[index2]) {
                        leadVal = nums1[index1++];
                    } else if (nums1[index1] > nums2[index2]) {
                        leadVal = nums2[index2++];
                    } else if (nums1[index1] < nums2[index2]) {
                        leadVal = nums1[index1++];
                    }
                }
                runningIndex++;
            }
            
            if (totalLength % 2 == 0) {
                return (double)(trailingVal + leadVal)/2;
            } else {
                return leadVal;
            }
        }
    }

Log in to reply
 

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