您的位置:首页 > 其它

合并有重复元素的两个有序数组,输出无重复元素

2014-10-23 13:46 411 查看
public class TwoArrMerge {
public static int[] mergeArr(int[] a, int[] b) {
int result[] = new int[a.length + b.length];
int i = 0, j = 0, k = 0;

while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
result[k++] = a[i++];
}else {
result[k++] = b[j++];
}
}
while (i < a.length) {
result[k++] = a[i++];
}
while (j < b.length) {
result[k++] = b[j++];
}

int m = 0;
int[] newResult = new int[result.length];
for (int l = 0; l < result.length; l++) {
if (l == 0) {
newResult[m++] = result[l];
}else if (result[l] > result[l-1])
newResult[m++] = result[l];
}
return newResult;
}

public static void main(String[] args) {
int[] a = {1,2,3,4,7};
int[] b = {1,3,4,5,6,7,8};
int[] result = mergeArr(a, b);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐