您的位置:首页 > 其它

[codevs3296]有序数组合并

2015-08-19 11:04 281 查看

题目描述 Description

合并两个有序数组A和B,使得结果依然有序。

进阶:合并两个有序数组A和B,假设A有n个数,B有m个数,A数组后面还有m个空余空间,需要将结果保存在A中。

请使用O(n)的算法完成

输入描述 Input Description

第一行输入两个整数n和m

第二行输入n个用空格隔开的整数表示数组A

第三行输入m个用空格隔开的整数表示数组B

输入保证A和B数组非递减

输出描述 Output Description

输出一行一共n+m个空格隔开的整数,即合并后的结果

样例输入 Sample Input

2 3

1 2

1 1 5

样例输出 Sample Output

1 1 1 2 5

数据范围及提示 Data Size & Hint

1<=n,m<=1000000

思路

用三个指针分别指向正在处理的两个数组和结果数组,最后需要看一看是不是全部比较完了,时间复杂度O(n);

var n,m,i,j,k,x:longint;
a,b,c:array[1..10000000] of int64;
begin
readln(n,m);
for i:=1 to n do read(a[i]);
for i:=1 to m do read(b[i]);
i:=1;//a的指针
j:=1;//b的指针
k:=1;//末尾的指针
while (i<>n+1)and(j<>m+1) do
begin
if a[i]<=b[j] then
begin
c[k]:=a[i];
inc(i);
inc(k);
end
else
begin
c[k]:=b[j];
inc(j);
inc(k);
end;
end;
// inc(k);
for x:=i to n do
begin
c[k]:=a[x];
inc(k);
end;
for x:=j to m do
begin
c[k]:=b[x];
inc(k);
end;
for i:=1 to (n+m) do write(c[i],' ');
end.


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: