A short solution by c++


  • 6
    V

    condition statement n == 0 || (m > 0 && A[m-1] > B[n-1]) to decide which number to insert

    class Solution {
    public:
        void merge(int A[], int m, int B[], int n) {
            int k = m + n;
            while (k-- > 0)
                A[k] = (n == 0 || (m > 0 && A[m-1] > B[n-1])) ?  A[--m] : B[--n];
        }
    };

  • 1
    W

    The basic idea is to merge backwards.

    Because Array A already has enough space to hold all the element, so we just need to find the last position to store the element when two arrays are merged, then we just need to compare element by element.

    here is my code:

    class Solution {
    public:
    void merge(int A[], int m, int B[], int n) {
        
        // idea is merge backwards
        int lastPos = m + n - 1;
        int endA = m-1;
        int endB = n-1;
        while (endA > -1 && endB > -1) {
            if (A[endA] > B[endB]) {
                A[lastPos] = A[endA];
                --endA;
            }
            else {
                A[lastPos] = B[endB];
                --endB;
            }
            --lastPos;
        }
        
        while (endB > -1) {
            A[lastPos] = B[endB];
            --endB;
            --lastPos;
        }
    }
    };
    

    Code is short does not mean it will be faster. What we do is make our code more self-understandable. Well, a short code maybe the target of a Geek.


Log in to reply
 

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