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

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

如果了解過歸并排序,這道題思路就非常簡單了。從兩個排序好的數組頭上取到兩個數字,兩個數字中的最小值即為剩余數字的最小值。 重復這個步驟就可以將兩個排序好的數組合并成一個有序數組。
對于這道題 只需要找到第 (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); //判斷總數是否為奇數
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容