LeetCode 4 Median of Two Sorted Arrays

LeetCode 1004

思路

一开始我用快速排序将两个数组重新排序,居然超时。
其实两个已经排好的数组用一个for循环排序就好了,效率O(m+n) ,而快排是O((m+n)*log(m+n))

但是题目上给的是O(log(m+n))的效率,应该是把O(m+n)都放过了。

class Solution {
public:
    int a[1000005];
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        
        int n=nums1.size();
        int m=nums2.size();
        int i=0,j=0;
        int tag=0;
        while(i<n&&j<m)
        {
           if(nums1[i]<=nums2[j])
                a[tag++]=nums1[i++];
           else 
               a[tag++]=nums2[j++];
        }
        while(i<n)
        {
            a[tag++]=nums1[i++];
        }
        while(j<m)
        {
            a[tag++]=nums2[j++];
        }
        
        if((n+m)%2==0)
            return 0.5*(a[(n+m)/2]+a[(n+m)/2-1]);
        else
            return 1.0*a[(n+m)/2];   
    }
    
    
};

posted @ 2018-11-09 11:28  Shendu.CC  阅读(88)  评论(0编辑  收藏  举报