leetcode 4
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)).
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
思路:
和merge sorted array一样,先把两个数组合并,然后找到中间的就可以啦
var findMedianSortedArrays = function(nums1, nums2) {
var m=nums1.length-1;
var n=nums2.length-1;
var count=m+n+1;
while(m>=0 && n>=0){
nums1[count--]=nums1[m]>nums2[n]?nums1[m--]:nums2[n--];
}
while(n>=0){
nums1[count--]=nums2[n--];
}
if((nums1.length)%2===0){
return (nums1[nums1.length/2]+nums1[(nums1.length/2)-1])/2
}else{
return nums1[((nums1.length)-1)/2]
}
};