Merge Two Sorted Arrays

描述

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

分析

代码

  1. // Merge Sorted Array
  2. // 时间复杂度O(m+n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. void merge(vector<int>& A, int m, vector<int>& B, int n) {
  6. int ia = m - 1, ib = n - 1, icur = m + n - 1;
  7. while(ia >= 0 && ib >= 0) {
  8. A[icur--] = A[ia] >= B[ib] ? A[ia--] : B[ib--];
  9. }
  10. while(ib >= 0) {
  11. A[icur--] = B[ib--];
  12. }
  13. }
  14. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/sorting/merge-sort/merge-two-sorted-arrays.html