美文网首页
LeetCode刷题系列之Median of Two Sorte

LeetCode刷题系列之Median of Two Sorte

作者: 溜达溜达就老了 | 来源:发表于2017-04-07 14:49 被阅读13次

Description

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

Solution

class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    if (0 == (nums1.size() + nums2.size())) {
        return 0.0;
    }

    vector<int> mergeVec;
    mergeVec.insert(mergeVec.end(), nums1.begin(), nums1.end());
    mergeVec.insert(mergeVec.end(), nums2.begin(), nums2.end());

    sort(mergeVec.begin(), mergeVec.end());

    int mergeVecSize = mergeVec.size();
    if (1 == mergeVecSize) {
        return mergeVec[0];
    }

    if (0 == (mergeVecSize % 2)) {
        int a = mergeVecSize / 2;
        int b = a - 1;
        return (mergeVec[a] + mergeVec[b])/2.0;
    } else {
        int a = mergeVecSize / 2;
        return mergeVec[a];
    }
}
};

相关文章

网友评论

      本文标题:LeetCode刷题系列之Median of Two Sorte

      本文链接:https://www.haomeiwen.com/subject/dlehattx.html