求两个有序数组的中值

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5


/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
var findMedianSortedArrays = function(nums1, nums2) {
    var result = [];
    var i=0,j=0,k=0;
    while(i<nums1.length && j<nums2.length){
        if(nums1[i] < nums2[j]){
            result[k++] = nums1[i++];
        }else{
            result[k++] = nums2[j++];
        }
    }
    
    while(i<nums1.length){
        result[k++] = nums1[i++];
    }
    while(j<nums2.length){
         result[k++] = nums2[j++];
    }
    if(result.length %2 !== 0){
        var index = (result.length-1)/2;
        return result[index];
    }else{
        var index = result.length/2;
        return  (result[index]+result[index-1])/2;
    }
    
};

问题可以转化为 合并两个有序数组 成为一个新的有序数组

原文地址:https://www.cnblogs.com/neverleave/p/5950761.html