Given sorted integer arrays A and B, merge B into a as one sorted array.
Note:
You could assume that A have enough space (size that's greater or equal to m + n) to the hold additional Eleme NTS from B. The number of elements initialized in A and B is m andn respectively.
According to the inertia idea of the merge sort, because the merge sort is given the two intervals of an array, the O (n) size of the auxiliary space is usually used. Ideas are as follows:
Class Solution {public: void merge (int a[], int m, int b[], int n) { int temp[m+n]; int i = 0, j = 0, t = 0; while (I < m && J < N) { if (A[i] < b[j]) temp[t++] = a[i++]; else temp[t++] = b[j++]; } while (I < m) temp[t++] = a[i++]; while (J < N) temp[t++] = b[j++]; while (--t >= 0) a[t] = temp[t]; }};
But the conditions given in the above topics are more flexible, so you can use the tail interpolation method, which eliminates the need for additional space overhead and is more concise in understanding:
Class Solution {public: void merge (int a[], int m, int b[], int n) { int ia = m-1, ib = n-1, icur = m + n-1; While (ia >= 0 && ib >= 0) a[icur--] = A[ia] > B[ib]? a[ia--]: b[ib--]; while (IB >=0) a[icur--] = b[ib--]; }};
(Daily algorithm) Leetcode--Merge Sorted Array (merge ordered array)