Title: Make two sorted arrays into a new sorted array, give a=[1,2,3,4],b=[2,4,5,6], return [1,2,2,3,4,4,5,6]
challenges
Can you optimize your algorithm if one of the arrays is large and the other array is small?
Idea: The two pointers point to the beginning of two arrays, each with a value of two pointers with a smaller number, the pointer moves back until one of the arrays ends, and the element after another array pointer is connected to the new array.
About the situation of the challenge if a[0]>b[b.length-1]| | A[a.length-1]<b[0], depending on the situation, you can directly connect a to the back of B (or b connected to the back of a)
The code is as follows
Public int[] Mergesortedarray (int[] A, int[] B) { int i=0; int j=0; int res[] = new Int[a.length+b.length]; int k=0; while (i<a.length&&j<b.length) { if (A[i]<=b[j]) { res[k++]=a[i++]; } else{ res[k++]=b[j++]; } } if (i!=a.length) {for (int a=i;a<a.length;a++) { res[k++]=a[a]; } } else{for (int b=j;b<b.length;b++) { res[k++]=b[b]; } } return res; }}
Java Merge two sorted arrays