# 3 line Java Solution

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

• ``````public void merge(int A[], int m, int B[], int n) {
int length = m+n;
while(n > 0) A[--length] = (m == 0 || A[m-1] < B[n-1]) ? B[--n] : A[--m];
}
``````

how about 2 lines :)

• ``````while(n>0)A[m+n-1]=(m==0||B[n-1]>A[m-1])?B[--n]:A[--m];
``````

Hey! Don't waste lines please! We just need 1 :)

• Crazy people~~

• haha, HR will love you man.

• OMGodness...........

• Your code doesn't work for following test case:

[1,2]
2
[3]
1

• WOW!!!!!!!!!!!!

• wrong code dosen't work for the case: [1] 1 [1] 1

• A minor detail:
A[k--] = (A[i]>B[j]) ? A[i--] : B[j--];
Won't both the options, A[i--] and B[j--], be computed in advance?

• Thanks for sharing your answer, but I still have some qurstions. why dont u check while (i>-1) A[k--]=A[i--];? I think there might be a siuation where there are still some elements left in the A after all B's elements are added into A.?

• @wxl163530 oK I get the idea , because the front of the A array is already sorted

• public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {

``````    ArrayList<Integer> res = new ArrayList<Integer>();
// Arrays.copyOf(nums1, m + n);

for(int num : nums2){
nums1[m++] = num;
}

Arrays.sort(nums1);

for(int num : nums1){
if(res.contains(num)){
res.remove(num);
}
}

int i = 0;
for(int num : res){
nums1[i++] = num;
}
``````

Is anyone can help me whats wrong wiht my code?
}
}

• @soloallen only the following code is required.

``````public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
for(int i = 0; i < n; i++)
nums1[i+m] = nums2[i];
Arrays.sort(nums1);
}
}
``````

Also, I think its better to use sorted set instead of ArrayList.

• @shamanthnorway but it takes O(N log N) time whereas other r only O(n)

• said in 3 line Java Solution:

while (j>-1) A[k--]=B[j--];

Nice solution. Thanks. Could anybody please explain why we need this statement:

while (j>-1) A[k--]=B[j--];

Thanks.

• @ynys Never mind, I figured out, for this case.

int[] a = {8, 9, 10, 11, 0, 0, 0,0,0,0,0};
int[] b = {1,2,3,4,5};

Thanks.

• @puuuuuuuuuuuuu your case is not the legal case here.

• it will out of bound when execute this line: A[k--]= (A[i]>B[j]) ? A[i--] : B[j--]; because the length of A is m, not k...but we cannot define a new result array, which is not satisfied the question requirements.

What should I do? Anyone can help?

• @fabrizio3 said in 3 line Java Solution:

``````while(n>0)A[m+n-1]=(m==0||B[n-1]>A[m-1])?B[--n]:A[--m];
``````

Hey! Don't waste lines please! We just need 1 :)

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