题目
编写一个函数,将两个已排序数组合并为一个数组。数组只包含整数。此外,必须对最终结果进行排序,不得有任何重复。
测试用例
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class SolutionTest {
@Test
public void basicTest() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 6 }, Kata.mergeArrays(new int[] { 1, 3, 5 }, new int[] { 2, 4, 6 }));
assertArrayEquals(new int[] { 2, 4, 6, 8 }, Kata.mergeArrays(new int[] { 2, 4, 8 }, new int[] { 2, 4, 6 }));
}
}
解题
My
import java.util.*;
public class Kata {
public static int[] mergeArrays(int[] first, int[] second) {
// 去重
HashSet hashSet = new HashSet();
for (int aFirst : first) {
hashSet.add(aFirst);
}
for (int aSecond : second) {
hashSet.add(aSecond);
}
// 利用TreeSet排序
Set set = new TreeSet(hashSet);
Integer[] integers = set.toArray(new Integer[]{});
// 排序去重后的结果数组
int[] result = new int[integers.length];
for (int i = 0; i < integers.length; i++) {
result[i] = integers[i];
}
return result;
}
}
Other
import java.util.stream.*;
public class Kata {
public static int[] mergeArrays(int[] first, int[] second) {
return IntStream.concat(IntStream.of(first),IntStream.of(second)).distinct().sorted().toArray();
}
}
import static java.util.stream.IntStream.*;
public class Kata {
public static int[] mergeArrays(int[] a, int[] b) {
return concat(of(a), of(b)).sorted().distinct().toArray();
}
}
import java.util.*;
public class Kata {
public static int[] mergeArrays(int[] first, int[] second) {
String str = Arrays.toString(first).replaceAll("[^0-9,-]","") + "," + Arrays.toString(second).replaceAll("[^0-9,-]","");
String[] arr = str.split(",");
int[] arrint = new int[arr.length];
for (int i =0; i
arrint[i] = Integer.valueOf(arr[i]);
}
Arrays.sort(arrint);
return Arrays.stream(arrint).distinct().toArray();
}
}
后记
other里我挑了简单,还有比我还要长的,看起来IntStream的方法真好用。