* 利用二路归并求两个数组合起来的中位数
* 求合并之后剔除重复元素
* 求两个数组的共同元素
public class MergeArr {
public static void main(String[] args) {
int[] a = {1, 2, 5, 6, 8, 9, 11};
int[] b = {5, 6, 8, 9, 88};
ArrayList arr = mergeArr(a, b);
for (int i = 0; i < arr.size(); i++) {
System.out.print(arr.get(i) + ",");
}
System.out.println();
ArrayList deleteArr = deleteReprtition(arr);
for (int i = 0; i < deleteArr.size(); i++) {
System.out.print(deleteArr.get(i) + ",");
}
System.out.println();
System.out.println(findMidNum(a, b));
System.out.println();
//获取共同元素
ArrayList arrayList = mergeArr(a,b);
ArrayList comArr = getCommonNum(arrayList);
for (int i = 0; i < comArr.size(); i++) {
System.out.print(comArr.get(i)+",");
}
}
/**
* 有序表的合并
*/
public static ArrayList mergeArr(int[] a, int[] b) {
int i = 0;
int j = 0;
ArrayList arr = new ArrayList<>();
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
arr.add(a[i]);
i++;
} else {
arr.add(b[j]);
j++;
}
}
//两个表
while (i < a.length) {
arr.add(a[i]);
i++;
}
while (j < b.length) {
arr.add(b[j]);
j++;
}
return arr;
}
/**
* 查两个有序表归并以后的中位数
*/
public static int findMidNum(int[] a, int[] b) {
int k = (a.length + b.length) % 2 == 0 ? (a.length + b.length) / 2 - 1 : (a.length + b.length + 1) / 2 - 1;
int i = 0;
int j = 0;
int midNum = 0;
while (i + j <= k) {
if (a[i] < b[j]) {
if (i + j == k) {
midNum = a[i];
}
i++;
} else {
if (i + j == k) {
midNum = b[j];
}
j++;
}
}
return midNum;
}
/**删除重复元素*/
public static ArrayList deleteReprtition(ArrayList arr) {
int i = 1;
int n = arr.size() - 1;
while (i < n) {
if (arr.get(i - 1) == arr.get(i)) {
arr.remove(i);
n--;
} else {
i++;
}
}
return arr;
}
/**获取公共元素*/
public static ArrayList getCommonNum(ArrayList arr) {
int i = 1;
int n = arr.size() - 1;
ArrayList comArr = new ArrayList();
while (i < n) {
if (arr.get(i - 1) == arr.get(i)) {
comArr.add(arr.remove(i));
n--;
} else {
i++;
}
}
return comArr;
}
}
打开App,阅读手记