美文网首页
4-median-of-two-sorted-arrays

4-median-of-two-sorted-arrays

作者: 本一和他的朋友们 | 来源:发表于2019-03-31 11:51 被阅读0次

Median of Two Sorted Arrays

There are two sorted arraysnums1andnums2of 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 assumenums1andnums2cannot 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

solution:

function findMedianSortedArrays(nums2, nums2) {
  let sumArr = nums.concat(nums2);
  let arrLength = sumArr.length;

  sumArr = sumArr.sort(function(a, b) {
    return a - b;
  });

  if (arrLength % 2 === 1) {
    return sumArr[Math.floor(arrLength / 2)];
  } else {
    return sumArr[arrLength / 2 - 1] + sumArr[arrLength / 2] / 2;
  }
}

相关文章

网友评论

      本文标题:4-median-of-two-sorted-arrays

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