Accepted c++ solution without any temporary variables.


  • 1

    In this problem, my thought is sort and save the array from right to left. What calls for special attention is that when B is empty, break the FOR loop, when A is empty, just copy the rest of the B to A. So the preliminary code is as follows:

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

  • 0

    What's more, LeetCodeOJ had accepted the following code:

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

Log in to reply
 

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