leetcode #4 Median of Two Sorted Arrays

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

  • 題目大意
    給定兩個有序數(shù)組,找到這兩個數(shù)組合并后的中位數(shù)。

如果了解過歸并排序,這道題思路就非常簡單了。從兩個排序好的數(shù)組頭上取到兩個數(shù)字,兩個數(shù)字中的最小值即為剩余數(shù)字的最小值。 重復(fù)這個步驟就可以將兩個排序好的數(shù)組合并成一個有序數(shù)組。
對于這道題 只需要找到第 (m+n)/2 個數(shù)字就可以了。
注意:當(dāng)總數(shù)為奇數(shù)時,中位數(shù)為(m+n)/2 個數(shù)字;當(dāng)總是為偶數(shù),中位數(shù)是第(m+n)/2 和 (m+n)/2-1 個數(shù)字的平均數(shù)

/**
 * @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); //算出中位數(shù)的位置。
    let last, current;
    while (i + j <= mid) {
        last = current;
        if (j >= nums2.length || nums1[i] < nums2[j]) { //j>=nums2.length 表示當(dāng)其中一個數(shù)組被取光后 只從另一個數(shù)組里面取。
            current = nums1[i++]
        } else {
            current = nums2[j++];
        }

    }
    return (nums1.length + nums2.length) % 2?current:((current + last) / 2); //判斷總數(shù)是否為奇數(shù)
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容