题解 | #合并两个有序的数组#(计算合并后长度,从后往前赋值,空间复杂度O(1))
合并两个有序的数组
http://www.nowcoder.com/practice/89865d4375634fc484f3a24b7fe65665
1.声明一个额外空间。 空间复杂度O(n)
class Solution { public: void merge(int A[], int m, int B[], int n) { vector<int> c(m+n); int i = 0, j = 0, k = 0; while(i < m && j < n){ if(A[i] < B[j])c[k++] = A[i++]; else c[k++] = B[j++]; } while(i < m)c[k++] = A[i++]; while(j < n)c[k++] = B[j++]; i = 0; for(int x : c){ A[i++] = x; } } };
- 一个已知数组从后往前开始赋值,空间复杂度为O(1) 且代码短
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 (i >= 0 && j >= 0){ A[k--] = A[i] > B[j] ? A[i--] : B[j--]; } while(j >= 0) A[k--] = B[j--]; } };