您的位置:首页 > 其它

[LeetCode]Merge Sorted Array

2013-10-27 22:57 190 查看

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和B,将B中的元素插入A(假设A有足够大的空间),保持有序性

Tip: A和B的大小已知,即合并完成后的数组大小确定。

将指针指向A和B的尾端,从数组的尾端(最大值)处开始合并。若B中仍有剩余元素,全部插入A的头部。

代码

class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(B==NULL || n==0)
return;

int p=m-1, q=n-1, cur=m+n-1;
while(p>=0 && q>=0)
{
if(A[p]>=B[q])
{
A[cur--] = A[p--];
}
else
{
A[cur--] = B[q--];
}
}
while(q>=0)
A[cur--] = B[q--];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: