Just simply merge two sorted arrays and keep monitoring the index of new array, and then return as early as possible


  • 0
    B
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int digits = nums1.length + nums2.length;
            int[] indexs = new int[2];
            int[] values = new int[2];
            if (digits%2 == 0) {
                indexs[0] = digits/2 - 1;
                indexs[1] = digits/2;
            }else {
                indexs[0] = digits/2;
                indexs[1] = digits/2;
            }
    
            
            int t = 0;
            int i = 0, j = 0;
            
            while (i < nums1.length && j < nums2.length) {
                while (i < nums1.length && j < nums2.length && nums1[i] < nums2[j]) {
                    t++; i++;
                    if (t - 1 == indexs[0]) {
                        values[0] = nums1[i-1];
                    }      
                    if (t - 1 == indexs[1]) {
                        values[1] = nums1[i-1];
                        return (values[0] + values[1])/2.0;
                    }                  
                }
                
                while (i < nums1.length && j < nums2.length && nums1[i] >= nums2[j]) {
                    t++; j++;
                    if (t - 1 == indexs[0]) {
                        values[0] = nums2[j-1];
                    }      
                    if (t - 1 == indexs[1]) {
                        values[1] = nums2[j-1];
                        return (values[0] + values[1])/2.0;
                    }               
                }
            }
            
            while (i < nums1.length){
                t++; i++;
                if (t - 1 == indexs[0]) {
                    values[0] = nums1[i-1];
                }      
                if (t - 1 == indexs[1]) {
                    values[1] = nums1[i-1];
                    return (values[0] + values[1])/2.0;
                }          
            }
            
            while (j < nums2.length){
                t++; j++;
                if (t - 1 == indexs[0]) {
                    values[0] = nums2[j-1];
                }      
                if (t - 1 == indexs[1]) {
                    values[1] = nums2[j-1];
                    return (values[0] + values[1])/2.0;
                }           
            }    
    
            return (values[0] + values[1])/2.0;
            
        }
    

Log in to reply
 

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