test instructions; Merge A, B with an ordered array into a, a space sufficient
Idea 1: The basic idea is simple, open up an extra array, space complexity and time complexity are O (N)
Code Listing 1:
public class Solution {public void merge (int a[], int m, int b[], int n) { if (n = = 0) return; if (M = = 0) { system.arraycopy (B, 0, A, 0, N); return; } int i =0, j=0, temp = 0,k=0; int [] C = new Int[a.length]; while (I < m && J < N) { while (I < M && A[i] <= b[j]) { c[k + +] = a[i + +]; } while (I < m && J < n && B[j] < A[i]) { c[k + +] = b[j + +]; } } if (I < m) { system.arraycopy (A, I, C, K, m-i); } if (J < n) { system.arraycopy (B, J, C, K, n-j); } System.arraycopy (C, 0, A, 0, c.length);} }
Idea 2: Reverse traversal from the tail, the large first into the array of the trailing space complexity of O (1), the time complexity of O (N)
Code Listing 2:
public class Solution {public void merge (int a[], int m, int b[], int n) { if (n = = 0) return; if (M = = 0) { system.arraycopy (B, 0, A, 0, N); return; } int tail = m + n-1; n--;m--; while (M >= 0 && n >=0) { A[tail--] = Math.max (A[m], b[n]); if (A[m] >= b[n]) m--; else n--; } while (n--> 0) { // a[tail--] = B[n]; } if (n >= 0) { system.arraycopy (b,0,a,0,n+1);}} }
Merge Sorted Array