用于跟踪唯一编号并将其丢弃的嵌套循环有助于解决此任务:
public static int countUnique(int ... n) {
Arrays.sort(n);
System.out.println(Arrays.toString(n));
int uniqueNumbers = 0;
for (int i = 0; i < n.length; i++) {
boolean unique = true;
for (int j = i + 1; j < n.length && n[i] == n[j]; j++, i++) {
unique = false;
}
if (unique) {
uniqueNumbers++;
}
}
return uniqueNumbers;
}
测试:
System.out.println(countUnique(2, 1, 2, 3, 4, 6, 4));
System.out.println(countUnique(2, 1, 2, 3, 4, 1, 4));
System.out.println(countUnique(2, 1, 2, 4, 4, 1, 4));
输出:
[1, 2, 2, 3, 4, 4, 6]
3
[1, 1, 2, 2, 3, 4, 4]
1
[1, 1, 2, 2, 4, 4, 4]
0
但是,由于对输入数组进行排序,该算法的复杂度为O(N log N)。
如果允许使用Set来跟踪重复项,使用Set::add在集合中已经存在元素时返回false的事实,这可以实现如下(另外,输入数组不需要要排序,所以这个算法有O(N)复杂度):
public static int countUniqueSets(int ... n) {
System.out.println(Arrays.toString(n));
Set<Integer> ones = new HashSet<>();
Set<Integer> dups = new HashSet<>();
for (int x : n) {
if (!ones.add(x)) {
dups.add(x);
}
}
System.out.println("distinct: " + ones);
System.out.println("duplicates: " + dups);
return ones.size() - dups.size();
}
相同测试的输出:
[2, 1, 2, 3, 4, 6, 4]
distinct: [1, 2, 3, 4, 6]
duplicates: [2, 4]
3
[2, 1, 2, 3, 4, 1, 4]
distinct: [1, 2, 3, 4]
duplicates: [1, 2, 4]
1
[2, 1, 2, 4, 4, 1, 4]
distinct: [1, 2, 4]
duplicates: [1, 2, 4]
0
另一种使用 Stream API 的方法是使用 Collectors.groupingBy + Collectors.counting 或 Collectors.summingInt 构建频率图,然后使用 frequency = 1 计算图中的条目:
public static int countUniqueStream(int ... n) {
System.out.println(Arrays.toString(n));
return (int) Arrays.stream(n)
.boxed()
.collect(Collectors.groupingBy(
x -> x,
Collectors.counting()
)) // Map<Integer, Long>
.entrySet()
.stream()
.filter(e -> 1 == e.getValue())
.count();
}
public static int countUniqueStreamInt(int ... n) {
System.out.println(Arrays.toString(n));
return Arrays.stream(n)
.boxed()
.collect(Collectors.groupingBy(
x -> x,
Collectors.summingInt(x -> 1)
)) // Map<Integer, Integer>
.entrySet().stream()
.filter(e -> 1 == e.getValue())
.collect(Collectors.summingInt(e -> 1));
}