美文网首页
Median of Two Sorted Arrays

Median of Two Sorted Arrays

作者: 飞飞廉 | 来源:发表于2017-11-29 18:36 被阅读0次

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]
    }
};

相关文章

网友评论

      本文标题:Median of Two Sorted Arrays

      本文链接:https://www.haomeiwen.com/subject/kvepbxtx.html