Is this a good solution? Merge Array A to B..


  • 0
    P
    public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        int c = m;
     
        for(int i=0;i<n;i++){
       
            A[c]  = B[i];
            c++;
         
        }
         Arrays.sort(A);
    
        
        
    }
    

    }

    Not sure if time complexity is good on my choice.., what do you guys think? :)


  • 2
    S

    I believe this is a tricky way to solve this problem, using sort function should be forbidden.

    Time complexity of sort will be O(N log N), but for this problem it could be O(N). N indicates the entire length of merged array.


  • 3
    X
    class Solution {
    public:
        void merge(int A[], int m, int B[], int n) {
            int indexA = m-1, indexB = n-1, index = m+n-1;
            while(indexB>=0 && indexA >=0 ){
                if(B[indexB] > A[indexA]) A[index--] = B[indexB--];
                else A[index--] = A[indexA--];
            }
            while(indexB>=0) A[index--] = B[indexB--];
        }
    };

  • 0
    L

    O(n+m) time will be better.

    class Solution {
    public:
    void merge(int A[], int m, int B[], int n) {
    int i = m - 1, j = n - 1;
    for (int k = m + n - 1; k >= 0; k--) {
    if (i < 0 || (j >= 0 && A[i] <= B[j])) A[k] = B[j--];
    else A[k] = A[i--];
    }
    }
    };


Log in to reply
 

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