Simple Javascript Solution for median of sorted arrays


  • 0
    S
    var findMedianSortedArrays = function(nums1, nums2) {
            var median = 0.0;
            var both = nums1.concat(nums2);
            both.sort(function(a, b){return a - b});
            var length = both.length;
            if(length%2 === 0) {
                median = (both[(length/2)-1] + both[length/2])/2;
            } else {
                median = (both[Math.floor(length/2)]);
            }
            return median;
    }
    

  • 1
    Z
    var findMedianSortedArrays = function(nums1, nums2) {
        var len=nums1.length+nums2.length;
    	var mid=Math.floor(len/2);
    	var remainder=len%2;
    	var assemble=[];
    	var median=0;
    	for (var i = 0;i <mid+remainder+!remainder;i++) {
    		if(nums1[0]==undefined){
    			assemble.push(nums2.shift());
    		}else if(nums2[0]==undefined){
    			assemble.push(nums1.shift());
    		}else{
    			assemble.push(nums1[0]>nums2[0]?nums2.shift():nums1.shift());
    		}
    	}
    	return remainder==0?(assemble.pop()+assemble.pop())/2:assemble.pop();
    };
    

Log in to reply
 

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