Code:
class Solution { public: void merge(int A[], int m, int B[], int n) { int i, j, count; for(i=0,j=0;i<m&&j<n;i++){ for(count=0;j<n&&A[i]>=B[j];j++) // count how many smaller than i count++; if(count>0){ // if there are some elements from B that need to insert into A for(int k=m-1;k>i-1;k--) // right-shift A[k+count]=A[k]; for(int k=0;k<count;k++) // insert A[i+k]=B[j-count+k]; m += count; i += count; } } if(j<n) // splice the rest B elements for(int k=0;k<n-j;k++) A[m+k]=B[k+j]; } };
Tricky Solution:
public class Solution { public void merge(int A[], int m, int B[], int n) { int i = m-1, j = n-1, k = m+n-1; while(k>=0){ if(j<0 || (i>=0 && A[i]>B[j])) A[k--]=A[i--]; else A[k--]=B[j--]; } } }