* 题目:
* 给定排序数组A和B,实现一个算法将B按排序顺序合并到A中。
* 介绍如下:
* 1.数组A和B的均为排序数组,数字按从小到大排列。
* 2.数组A的的长度为n,其中前m个为数字,后n -m个为None;数组B的长度为n - m。
* 3.需要将数组B的数字依次添加到数组A中,添加元素后A的依旧是排序数
* 输入描述
* 第一行为两个数字n, m(1 <n, m<1000),空格隔开,含义如题干所示。
* 第二行为n个数字,数组A中的前n项元素。
* 第二行为n个数字,数组A中的前n项元素。
*
*
* 思路:
* 我们可以定义一个新数组用来存放合并的元素 然后再重新覆盖到数组A中输出即可
* 一看到升序数组我们就可以想到使用双指针,
* 具体思路为:
* 1:定义双指针,先判断当前数组元素是否取完,如果数组A中的元素取完了,就直接取数组B 反之
* 2:对比A和B中的元素,双指针就分别指2个数组的下标,对比两个数组的元素谁更小,谁小谁放入新数组中
* 如果一样大,放谁都可以,我们判断条件可以写为if(A[i]>B[i]) 这样就只判断A大于B的时候的逻辑 而B>=A的逻辑就是else了
*/
public class 合并排序数组 {
public static void main(String[] args) {
// 第一行 2个数字 n 和 m 全部数组长度和第一个数组的长度
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] a = new int[n];
int[] b = new int[n-m];
// 第一个数组中存值
for (int i = 0; i < m; i++) {
a[i]= sc.nextInt();
}
// 第二个数组中存值
for (int i = 0; i < n-m; i++) {
b[i] = sc.nextInt();
}
merge(a,m,b,n-m);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
private static void merge(int[] nums1, int m, int[] nums2, int n) {
int k = m+n;
int[] temp = new int[k];
// index是循环条件 不管 indexNums1-2是双指针
for (int index = 0, indexNums1 = 0, indexNums2 = 0; index < k; index++) {
// 如果数组1取完就取数组2 反之
if (indexNums1 >= m) {
temp[index] = nums2[indexNums2++];
} else if (indexNums2 >= n) {
temp[index] = nums1[indexNums1++];
}
// 开始对比元素 nums1元素小于nums2 取nums1
else if (nums1[indexNums1] < nums2[indexNums2]) {
temp[index] = nums1[indexNums1++];
} else {
temp[index] = nums2[indexNums2++];
}
}
// 把新数组的元素重新覆盖到数组1中。
for (int i = 0; i < k; i++) {
nums1[i] = temp[i];
}
}
}
蓝桥杯 Java 合并排序数组
最新推荐文章于 2024-07-22 14:15:06 发布