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

• My solution,

``````public class Solution {
public void merge(int A[], int m, int B[], int n) {
System.arraycopy(B, 0, A, m, n);
Arrays.sort(A);
}
}``````

• Just to reminder, this tricky way won't be allowed by interviewer.

• ``````    public void merge(int A[], int m, int B[], int n) {

for(int i = m + n - 1; i>=0; i--)
{
if( m>0 && n>0)
{
if(B[n-1] > A[m-1])
{
A[i] = B[n-1];
n--;
}
else
{
A[i] = A[m-1];
m--;
}
}
else if(m>0)
{
A[i] = A[m-1];
m--;
}
else if(n>0)
{
A[i] = B[n-1];
n--;
}
}

}``````

• Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example

• Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example

• ``````class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int p = m-1, q = n-1, i = m+n-1;
while ( q>=0 ) {
if ( p<0 || B[q] >= A[p] )
A[i--] = B[q--];
else
A[i--] = A[p--];
}
}
};``````

• Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example

• it don't pass my my local machine when i put A=[] and B=[1],advisor?

• hahaha, you so funny, I kinda like this solution, well, in practice.

• Thanks， I see， just for fun， heihei

• This post is deleted!

• This post is deleted!

• It shouldn't pass because A is supposed to have enough space for all of the elements m + n. In your example, A has 0 space, but there exists one element, which is a contradiction to the prompt.

• This is pretty easy understanding code. Interviewer will like this easy maintenance code.
Why people try to shorten their code too much!

• yeah, just for fun

• can you please explain at the end of while loop ,why "nums1[j--] = nums2[j--]" cannot be true?

• that's the wonderful answer.thx for implement my thought which I didn't figure it out.

• which while loop do u mean?

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