LeetCode:Merge Sorted Array

题目链接

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.                                              本文地址

分析:由于题目假设了A可以存放所有A和B的元素,因此我们可以从两个数组的尾部开始遍历,将较大者放入数组A尾部(尾部下标递减)。时间复杂度O(m+n),常数空间复杂度

 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n) {
 4         //同时从两个数组尾部开始遍历,将较大者放在A的尾部
 5         int i = m+n-1, ia = m-1, ib = n-1;
 6         while(ia >= 0 && ib >= 0)
 7             A[i--] = A[ia] > B[ib] ? A[ia--] : B[ib--];
 8         while(ib >= 0)A[i--] = B[ib--];
 9     }
10 };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3451948.html

你可能感兴趣的:(LeetCode)