4. Median of Two Sorted Arrays

Problem:

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

You may assume nums1 and nums2 cannot be both empty.

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

思路

利用归并排序的原理将两个数组按序合并为一个数组,然后求中位数即可。

Solution (C++):

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    int m = nums1.size(), n = nums2.size();
    vector<int> res{};
    int i = 0, j = 0;
    while (i < m && j < n) {
        if (nums1[i] < nums2[j]) {
            res.push_back(nums1[i]);
            ++i;
        }
        else {
            res.push_back(nums2[j]);
            ++j;
        }
    } 
    while (i < m) { res.push_back(nums1[i]); ++i; }
    while (j < n) {res.push_back(nums2[j]); ++j; }
    
    return (m+n-1)%2 ? double(res[(m+n)/2-1] + res[(m+n)/2]) / 2 : res[(m+n-1)/2];        
}

性能

Runtime: 24 ms  Memory Usage: 8.3 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

posted @ 2020-03-27 18:17  littledy  阅读(119)  评论(0编辑  收藏  举报