参考:https://blog.csdn.net/jike11231/article/details/120851148
package Sort;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
// 多个有序数组,合并成一个并排序和去重
/*
1、因为是有序数组,不需要重新排序。合并时通过每个数组的首尾元素判断递增还是递减;指针用flag标识,判断p++还是p--
2、去重:LinkList,合并时一边去重,一边加入list,不会浪费数组空间(但是return时要转换成int数组类型,后面合并方便)
3、多个数组:先合并2个数组,其它数组递归即可 / 循环合并
时间复杂度:O(mn),m是数组长度,n是数组数量?
n*log(2n)?
*/
public class More {
public static void main(String[] args) {
int[] a = {0, 1, 2, 3};
int[] b = {2, -1};
int[] c = {4, 5, 7, 90};
int[] d = {2, 4, 5};
// int[] merge1 = sort(a, b);
// int[] merge2 = sort(d, c);
// int[] merge = sort(merge1, merge2);
// System.out.println(Arrays.toString(merge));
int[] result = sort(a, b, c, d);
System.out.println(Arrays.toString(result));
}
// 多数组整合
private static int[] sort(int[]... data) {
if (data == null) {
return null;
}
int[] result = data[0];
// if (data.length == 1) {
// return result;
// }
// for (int i = 1; i < data.length; i++) {
// result = sort(result, data[i]);
// }
for (int i = 0; i < data.length; i++) {
result = sort(result, data[i]);
}
return result;
}
// 两个有序数组组合并去重
private static int[] sort(int[] a, int[] b) {
// LinkedList,去重用,放组合去重后的数组
List<Integer> list = new LinkedList();
//ab数组分别通过首尾元素判断递增还是递减;指针用flag标识,判断p++还是p--
int a_start = a[0] <= a[a.length - 1] ? 0 : a.length - 1;
int a_flag = a[0] <= a[a.length - 1] ? 1 : -1;
int b_start = b[0] <= b[b.length - 1] ? 0 : b.length - 1;
int b_flag = b[0] <= b[b.length - 1] ? 1 : -1;
while (a_start >= 0 && a_start < a.length && b_start >= 0 && b_start < b.length) {
if (a[a_start] < b[b_start]) {
list.add(a[a_start]);
a_start += a_flag;
} else if (a[a_start] > b[b_start]) {
list.add(b[b_start]);
b_start += b_flag;
} else if (a[a_start] == b[b_start]) {
list.add(a[a_start]);
a_start += a_flag;
b_start += b_flag;
}
}
// 还没加进去list里的,加一下
if (a_start >= a.length || a_start < 0) {
while (b_start < b.length && b_start >= 0) {
list.add(b[b_start]);
b_start += b_flag;
}
} else if (b_start >= b.length || b_start < 0) {
while (a_start < a.length && a_start >= 0) {
list.add(a[a_start]);
a_start += a_flag;
}
}
return list.stream().mapToInt(Integer::intValue).toArray(); // 转成Int
}
}