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 的有序數組 nums1 和 nums2 。
請找出這兩個有序數組的中位數。要求算法的時間複雜度爲 O(log (m+n)) 。

示例 1:
nums1 = [1, 3]
nums2 = [2]
中位數是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
中位數是 (2 + 3)/2 = 2.5

分析
歸併兩個數組,取新數組中間數組的中間元素。(這個算法的複雜度應該是O(n)的,不知道爲什麼也過了)

c++實現

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int max = pow(2,31)-1;
        int i = 0,j = 0,a = 0,b = 0;
        double result;
        vector<int> num;
        while (i < nums1.size() || j < nums2.size())
        {
            a = (i < nums1.size() ? nums1[i] : max);
            b = (j < nums2.size() ? nums2[j] : max);
            num.push_back(a < b ? a : b);
            a < b ? i++ : j++;
        }
        if (num.size()%2 == 0)
            result = (num[num.size()/2-1]+num[num.size()/2])/2.0;
        else
            result = num[num.size()/2];
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章