xinyu04

导航

LeetCode Median of Two Sorted Arrays 排序

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

The overall run time complexity should be \(O(\log (m+n))\).

Solution

简单排序即可:

点击查看代码
class Solution {
private:
    vector<int> vc;
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        for(int i=0;i<nums1.size();i++)vc.push_back(nums1[i]);
        for(int i=0;i<nums2.size();i++)vc.push_back(nums2[i]);
        sort(vc.begin(),vc.end());
        if(vc.size()==0)return 0;
        if(vc.size()%2){
            return 1.0*vc[(vc.size()-1)/2];
        }
        else{
            return 0.5*(vc[vc.size()/2]+vc[vc.size()/2-1]);
        }
    }
};

posted on 2022-07-10 02:50  Blackzxy  阅读(6)  评论(0编辑  收藏  举报