There are two sorted arrays nums1 and nums2 of size m and n respectively.
You may assume nums1 and nums2 cannot be both empty.
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 arr = nums1.concat(nums2);
var numsArr = arr.sort(function sequence(a,b){
return a - b;
});
var len = numsArr.length;
var middle = 0;
if(len%2 == 0) {
middle = (numsArr[parseInt(len/2)]+numsArr[parseInt(len/2)-1])/2;
} else {
middle = numsArr[parseInt(len/2)]
}
return middle;
};