美文网首页
leetcode #4 Median of Two Sorted

leetcode #4 Median of Two Sorted

作者: huntriver | 来源:发表于2017-07-04 15:11 被阅读0次

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)).

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

  • 题目大意
    给定两个有序数组,找到这两个数组合并后的中位数。

如果了解过归并排序,这道题思路就非常简单了。从两个排序好的数组头上取到两个数字,两个数字中的最小值即为剩余数字的最小值。 重复这个步骤就可以将两个排序好的数组合并成一个有序数组。
对于这道题 只需要找到第 (m+n)/2 个数字就可以了。
注意:当总数为奇数时,中位数为(m+n)/2 个数字;当总是为偶数,中位数是第(m+n)/2 和 (m+n)/2-1 个数字的平均数

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */

var findMedianSortedArrays = function (nums1, nums2) {
    let i = 0;
    let j = 0;
    let mid = parseInt((nums1.length + nums2.length) / 2); //算出中位数的位置。
    let last, current;
    while (i + j <= mid) {
        last = current;
        if (j >= nums2.length || nums1[i] < nums2[j]) { //j>=nums2.length 表示当其中一个数组被取光后 只从另一个数组里面取。
            current = nums1[i++]
        } else {
            current = nums2[j++];
        }

    }
    return (nums1.length + nums2.length) % 2?current:((current + last) / 2); //判断总数是否为奇数
}

相关文章

网友评论

      本文标题:leetcode #4 Median of Two Sorted

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