题目:
Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate.
解析:
编写一个函数,将两个排序后的数组合并为一个数组。数组只包含整数。此外,最终结果必须进行排序,不能有任何重复。
本题主要考察数组合并、去重、排序等问题
我的答案
public static int[] mergeArrays(int[] first, int[] second) {
Integer[] firstInteger = new Integer[first.length];//将int[]数组转化为Integer[]
for (int i=0;i<firstInteger.length;i++){
firstInteger[i] =first[i];
}
Integer[] secondInteger = new Integer[second.length];
for (int i=0;i<secondInteger.length;i++){
secondInteger[i] =second[i];
}
List<Integer> firstList = Arrays.asList(firstInteger);//将数组转化为list进行合并
List<Integer> secondList = Arrays.asList(secondInteger);
List<Integer> all = new ArrayList();
all.addAll(firstList);
all.addAll(secondList);
List<Integer> result = new ArrayList();//去重
for (int i=0;i<all.size();i++){
if(!result.contains(all.get(i))){
result.add(all.get(i));
}
}
//转化会int类型,本来想用result.toArray转化为数组,但返回类型为Object[],要求返回int[]
int[] res = new int[result.size()];
for (int i=0;i<result.size();i++){
res[i] =result.get(i).intValue();
}
Arrays.sort(res);
return res;
}
最优答案
public static int[] mergeArrays(int[] first, int[] second) {
return IntStream.concat(IntStream.of(first),IntStream.of(second)).distinct().sorted().toArray();
}