leetcode 4 Median of Two Sorted Arrays(有坑待填)

来源:互联网 发布:仁霸玻璃优化软件 编辑:程序博客网 时间:2024/05/18 02:46

题目:

https://leetcode.com/problems/median-of-two-sorted-arrays/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

给定两个有序数组,求两个数组合并的中位数

思路:

题目要求用O(log(m+n))的算法,暂时不会,以后补。
O(m+n)的算法:用归并排序的方式合并两个数组,然后可以直接取其中位数

代码:

O(m+n)

class Solution {public:    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {        vector<int> ans;        ans.reserve(nums1.size() + nums2.size());        vector<int>::size_type i = 0, j = 0;        while(i < nums1.size() && j < nums2.size())        {            if(nums1[i] < nums2[j])                ans.emplace_back(nums1[i++]);            else                ans.emplace_back(nums2[j++]);        }        while(i < nums1.size())            ans.emplace_back(nums1[i++]);        while(j < nums2.size())            ans.emplace_back(nums2[j++]);        if(ans.size() % 2 != 0)            return ans[ans.size()/2];        else            return (ans[ans.size()/2-1] + ans[ans.size()/2]) / 2.0;    }};