本节内容是归并,将两个数组融合到一起,并且是排序好的。
用普通for循环也能达到数组融合的效果,但是效率太差,容易被企业pass掉,所以就不介绍了
public class Test {
/**
* 本节内容是归并,将两个数组融合到一起,并且是排序好的。
* 用普通for循环也能达到数组融合的效果,但是效率太差,容易被企业pass掉,所以就不介绍了
* @param args
*/
public static void main(String[] args) {
// 有两个数组
int[] arr1 = {1,7,10};
int[] arr2 = {2,8,12,32,45};
// 把两个数组合并成一个数组,还有序
int[] concat = concat(arr1,arr2);
// 遍历
for (int i : concat) {
System.out.println(i + " ");
}
}
private static int[] concat(int[] a1,int[] a2){
// 创建一个新数组
int[] temp = new int[a1.length + a2.length];
// 三个指针,left指向a1,right指向a2,newIndex指向temp
int left = 0;
int right = 0;
int newIndex = 0;
// 退出循环的机制
// a1.length和a2.length都不等于他们的指针时进入这个循环
while (a1.length != left && a2.length != right){
// 如果a1大于a2,那么temp等于小的那个,也就是a2,a2的指针向右移一位
if (a1[left] > a2[right]) {
temp[newIndex] = a2[right];
right++;
}else {
// 道理同上
temp[newIndex] = a1[left];
left++;
}
// temp得到了一位数,所以它的指针向前进一位
newIndex++;
}
// 当a1的长度等于它的指针
if (a1.length == left){
// 数组的长度就从a2开始,并且小于a2的长度
for (int i = right; i < a2.length; i++) {
// temp的长度++等于a2
temp[newIndex++] = a2[i];
}
}
// 同上
if (a2.length == right){
for (int i = left; i < a1.length; i++) {
temp[newIndex++] = a1[i];
}
}
return temp;
}
}