Is it a good way that i just use sort(vec.begin(), vec.end())?


  • 0
    C

    I just added the integers to a vector and use sort function, then find the median.

    Std Sort() uses quick sort essentially. It will be fast for quick sort if new array is generated from two sorted arrays.

    The time costed is 372 ms.

    The code is below:

    double findMedianSortedArrays(int A[], int m, int B[], int n)
    {
    vector<int> vecTmp;
    double dbReturn = 0.0;
    for (int i = 0; i < m; i++){
    vecTmp.push_back(A[i]);
    }
    for (int i = 0; i < n; i++){
    vecTmp.push_back(B[i]);
    }

        sort(vecTmp.begin(), vecTmp.end());
        if ((m + n)%2 == 0){
            int nM = (m + n)/2;
            dbReturn = ((double)vecTmp[nM - 1] + (double)vecTmp[nM])/2;
        }
        else{
            dbReturn = vecTmp[(m + n)/2];
        }
        
        return dbReturn;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.