题解 | #合并两个有序的数组#
合并两个有序的数组
https://www.nowcoder.com/practice/89865d4375634fc484f3a24b7fe65665
class Solution { public: void merge(int A[], int m, int B[], int n) { int C[m + n]; int pa = 0, pb = 0, pc = 0; if (m == 0 || n == 0) { if (n == 0) return; if (m == 0) { for (int i = 0; i < n; i++) { A[i] = B[i]; } return; } } else { A[m] = 100; B[n] = 100; while (pc != m + n) { if (A[pa] < B[pb]) { C[pc] = A[pa]; pa++; pc++; } else if (A[pa] > B[pb]) { C[pc] = B[pb]; pb++; pc++; } else { C[pc] = B[pb]; C[++pc] = B[pb]; pa++; pb++; pc++; } } } for (int i = 0; i < m + n; i++) { A[i] = C[i]; } } };
题有对于数组中元素大小的限制,所以边界情况变得相对简单。