题目:合并两个有序数组.
实现思想:为了考虑算法实现的效率,采用数组从后往前合并,先计算出合并后的数组的长度,再设置一个索引从数组的末尾往前赋值。
具体实现:
<span style="font-family:Microsoft YaHei;font-size:18px;">package com.demo.combiner;
public class Combine {
public static void combine(int[] a1, int[] a2) {
if (a1 == null || a2 == null || (a1.length + a2.length) > 1024) {
return;
}
int length1 = a1.length - 1; //数组1的索引
int length2 = a2.length - 1; //数组2的索引
int length = length1 + length2 + 2; //新数组的长度
int len = length - 1; //新数组的索引
int[] array = new int[length];
//循环数组1和数组2中的值
while (length1 >= 0 && length2 >= 0) {
//对数组1和数组2中的值进行比较
if (a1[length1] >= a2[length2]) {
//数组1中的大就将数组1中的值存至新数组
array[len--] = a1[length1--];
} else {
//数组2中的大就将数组1中的值存至新数组
array[len--] = a2[length2--];
}
}
while (length1 >= 0) {
array[len--] = a1[length1--];
}
while (length2 >= 0) {
array[len--] = a1[length2--];
}
for (int i=0; i<array.length;i++) {
System.out.print(array[i] + " ");
}
System.out.println();
return;
}
public static void main(String[] args) {
int[] a1 = new int[] { 1, 3, 4, 5 };
int[] a2 = new int[] { 2, 4, 6, 10 };
combine(a1, a2);
}
}
</span>