一点小失误,基本一次过吧,这段程序不好,参考C#
1 class Solution { 2 public: 3 void merge(int A[], int m, int B[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector C(m); 7 for (int i = 0; i < m; i++) C[i] = A[i]; 8 int p = 0; 9 int q = 0;10 int beg = 0;11 while (p < m && q < n) {12 A[beg++] = min(C[p], B[q]);13 if (C[p] < B[q]) p++;14 else q++;15 }16 if (p == m) {17 for (int i = q; i < n; i++) A[beg++] = B[i];18 }19 if (q == n) {20 for (int i = p; i < m; i++) A[beg++] = C[i];21 }22 }23 };
C#
1 public class Solution { 2 public void Merge(int[] nums1, int m, int[] nums2, int n) { 3 for (int i = m+n-1; i >= 0; i--) { 4 if (m == 0) nums1[i] = nums2[--n]; 5 else if (n == 0) break; 6 else if (nums1[m-1] < nums2[n-1]) nums1[i] = nums2[--n]; 7 else nums1[i] = nums1[--m]; 8 } 9 }10 }