天天看點

LeetCode——尋找兩個有序數組的中位數

題目:

給定兩個大小為 m 和 n 的有序數組 nums1 和 nums2。

請你找出這兩個有序數組的中位數,并且要求算法的時間複雜度為 O(log(m + n))。

你可以假設 nums1 和 nums2 不會同時為空。

示例 1:

nums1 = [1, 3]

 nums2 = [2]

則中位數是 2.0

示例 2:

nums1 = [1, 2]

nums2 = [3, 4]

 則中位數是 (2 + 3)/2 = 2.5

思路:

題目中限制了算法的時間複雜度為O(log(m + n)),就要求我們在最多在一次周遊中将兩個數組聯合排序

由于是兩個有序數組,直接從前面開始比較就可以。

定義sorted為排序後的數組,分别使用 i, j标記num1,num2目前比較的數字索引,将較小的數字填入sorted,知道其中一個數組全部并入到sorted中,然後将剩餘的數組拼接在sorted後面,最後隻要取中位數就可以了。

代碼如下:

var findMedianSortedArrays = function(nums1, nums2) {
    let sorted = [], len1 = nums1.length, len2 = nums2.length;
    if(len1 === 0 || len2 === 0){
        sorted = nums1.concat(nums2)
    }else{
        let i = 0, j = 0;
        while(i<len1 && j<len2){
            if(nums1[i] <= nums2[j]){
                sorted.push(nums1[i]);
                i++;
            }else{
                sorted.push(nums2[j]);
                j++
            }
        }
        if(i === len1){
            sorted = sorted.concat(nums2.slice(j))
        }
        if(j === len2){
            sorted = sorted.concat(nums1.slice(i))
        }
    }
    return (len1+len2)%2==0?(sorted[(len1+len2)/2]+sorted[(len1+len2)/2-1])/2:sorted[Math.ceil((len1+len2)/2)-1];
};
           

代碼位址:github位址