您的位置:首页 > 其它

LintCode之6 合并排序数组

2017-11-24 16:11 369 查看
题目来源:合并排序数组

题目描述:

合并两个排序的整数数组A和B变成一个新的数组。

样例:

给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]

Java代码:

public int[] mergeSortedArray(int[] A, int[] B) {
// Write your code here
int[] result = new int[A.length+B.length];
int acount=0,bcount=0,rcount=0;
while (acount<A.length&&bcount<B.length) {
if (A[acount]<=B[bcount]) {
result[rcount++]=A[acount];
acount++;
continue;
}
if (A[acount]>B[bcount]) {
result[rcount++]=B[bcount];
bcount++;
continue;
}
}
if (acount>=A.length&&bcount<B.length) {
while (bcount<B.length) {
result[rcount++] = B[bcount++];
}
}
if (acount<A.length&&bcount>=B.length) {
while (acount<A.length) {
result[rcount++] = A[acount++];
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: