题目
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 (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.
解题思路
合并两个数组为一个有序数组,这题也很简单,唯一考查的地方就是怎么处理数组,是从前往后还是从后往前。一般情况,从后往前的效率比从前往后高,也要省不少事。代码如下,从后开始合并。
代码实现:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
if(B==NULL || n<=0) return ;
if(A==NULL || m<=0) {
for(; n>0; --n)
A[n-1] = B[n-1];
return ;
}
int i=m-1, j=n-1, k = m+n-1;
while(i>=0 && j>=0){
if(A[i]>B[j])
A[k--] = A[i--];
else
A[k--] = B[j--];
}
while(j>=0)
A[k--] = B[j--];
}
};
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:
swalge
或者扫描下方二维码关注我
(转载文章请注明出处: http://blog.youkuaiyun.com/swagle/article/details/29378433 )