Open blueWind123731 opened 3 years ago
归并排序
var findMedianSortedArrays = function(nums1, nums2) {
function getMid(arr){
let len = arr.length
return (len%2==0?(arr[len/2]+arr[(len/2-1)])/2:arr[parseInt(len/2)])
}
if(!nums1.length){
return getMid(nums2)
}
if(!nums2.length){
return getMid(nums1)
}
if(nums1.length&&nums2.length){
let list = []
let i=0,j=0
while(i<nums1.length&&j<nums2.length){
if(nums1[i]<=nums2[j]){
list.push(nums1[i])
i++
}else {
list.push(nums2[j])
j++
}
}
list = nums1[i]?list.concat(nums1.slice(i)):list
list = nums2[j]?list.concat(nums2.slice(j)):list
return getMid(list)
}
};
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. Follow up: The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Example 3:
Input: nums1 = [0,0], nums2 = [0,0] Output: 0.00000
Example 4:
Input: nums1 = [], nums2 = [1] Output: 1.00000
Example 5:
Input: nums1 = [2], nums2 = [] Output: 2.00000
https://leetcode.com/problems/median-of-two-sorted-arrays/