Degree
Easy ★ (*´╰╯`๓)♬
Description:
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)).
Example1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Ideas
- 将两个数组合并成一个数组并按大小顺序排序
- 选取数组的中间两个数或一个数
- 算出平均数
Code
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function(nums1, nums2) {
function compare(val1,val2){
return val1-val2;
};
let nums3 = nums1.concat(nums2).sort(compare);
let lowMiddle = Math.floor((nums3.length - 1) / 2);
let highMiddle = Math.ceil((nums3.length - 1) / 2);
let median = (nums3[lowMiddle] + nums3[highMiddle]) / 2;
return median;
};