Iterative and concise Java solution


  • 0
    T
    public class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    
            int[] combined = merge(nums1, nums2);
            
            return (combined.length % 2 == 0) ? (combined[(combined.length / 2) - 1] + combined[combined.length / 2]) / 2.0 : combined[combined.length / 2];
        
        }
        
        private int[] merge(int[] nums1, int[] nums2) {
            
            int[] combined = new int[nums1.length + nums2.length];
            
            int i = 0, j = 0, k = 0;
            
            while (i < nums1.length && j < nums2.length) combined[k++] = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++];
            while (i < nums1.length) combined[k++] = nums1[i++];
            while (j < nums2.length) combined[k++] = nums2[j++];
            
            return combined;
    
        }
    }
    

Log in to reply
 

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