题目:

合并两个排序的整数数组A和B变成一个新的数组。

 

你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。

解答:

倒过来进行添加,正着添加可能需要移位,会比较麻烦

 

    1. class Solution {
      public:
      /**
      * @param A: sorted integer array A which has m elements, 
      * but size of A is m+n
      * @param B: sorted integer array B which has n elements
      * @return: void
      */
      void mergeSortedArray(int A[], int m, int B[], int n) {
      // write your code here
      int pos = m + n - 1;
      int posA = m - 1;
      int posB = n - 1;
      while (posA >= 0 && posB >= 0) {
      if (A[posA] > B[posB]) {
      A[pos--] = A[posA--];
      } else {
      A[pos--] = B[posB--];
      }
      }
      while (posA >= 0) {
      A[pos--] = A[posA--];
      }
      while (posB >= 0) {
      A[pos--] = B[posB--];
      }
      }
      };

       
 posted on 2018-01-07 19:32  做个快乐的自己  阅读(177)  评论(0编辑  收藏  举报