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)).
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(num1, num2) {
var midium=0;
//合并两个数组
var num3=num1.concat(num2);
var compare = function (x, y) {//比较函数
if (x < y) {
return -1;
} else if (x > y) {
return 1;
} else {
return 0;
}
}
//排序
num3.sort(compare)
var flag=num3.length%2;
//处理数组元素个数为奇数和偶数的情况
if(flag==1){
midium=num3[Math.floor(num3.length/2)];
return midium;
}else{
midium= (num3[num3.length/2]+num3[num3.length/2-1])/2;
return midium;
}
};