Median of Two Sorted Arrays---两个有序数组查找中位数

题意为:

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

我的第一想法是两数组合并并排序,然后找中位数,判断合并后的数组长度是否为2的倍数,如果是2的倍数,则把最中间两位数相加相加除以2返回,如果不是2的倍数,直接返回中间那位数.代码如下:

var findMedianSortedArrays = function(nums1, nums2) {
    var arr = nums1.concat(nums2);
    arr = arr.sort(function(a,b){
        return a-b;
    });
    var len = arr.length;
    if(len%2==0){
        return (arr[len/2] + arr[len/2-1])/2;
    }else{
        return arr[(len-1)/2];
    }
}

此方法较费时,所以再想想其他解决办法,进行优化,未完待续............

你可能感兴趣的:(JavaScript,leetcode)