刷题4. Median of Two Sorted Arrays

I, entitled

Median of Two Sorted Arrays, specific search on their own.

This subject, I looked at, after some thought, I think is not very complicated to implement.

But to be bug free is not difficult, the biggest problem is the performance issue.

The performance of only 42% of the way, take up too much memory. Need to be further optimized! ! !

Second, the subject, I realized

Submitted 2:

1st: Wrong Answer

The second: finally right

Here is my complete code implementation, need take:

#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m = nums1.size();
        int n = nums2.size();
        float f = 0;
        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++; 
        }
            
        if((m+n) %2 == 0){
            //总共有偶数个,取中间2个平均值
            f = res[(m+n)/2-1]+res[(m+n)/2];
            return f/2;
        }else{
            //找到中间值
            return res[(m+n)/2];
        }
    }
};

int main(){
    vector<int> v1 = {1,3};
    vector<int> v2 = {2};
    Solution s;
    cout<<s.findMedianSortedArrays(v1,v2)<<endl;
    
    v1 = {1,2};
    v2 = {3,4};
    cout<<s.findMedianSortedArrays(v1,v2)<<endl;
    return 0;
}

Third, improve

Let me think about ...

Guess you like

Origin www.cnblogs.com/siweihz/p/12231449.html