我目前正在解决以下编程问题:Find the unique number语句是:
有一个包含一些数字的数组。所有数字都相等,除了 一。尝试找到它!
Kata.findUniq(new double [] {1,1,1,2,1,1}); // => 2 Kata.findUniq(new double [] {0,0,0.55,0,0}); // => 0.55
保证数组包含3个以上的数字。
测试包含一些非常大的数组,因此请考虑性能。
首先,我的想法是获取所有元素的频率作为映射,然后返回频率值为1的键。
我写了以下内容:
import java.util.stream.*;
public class Kata {
public static double findUniq(double arr[]) {
Map<Double,Long> frequencies = Arrays.stream(arr)
.collect(Collectors.groupingBy(n -> n,Collectors.counting()));
System.out.println("Map: "+map);
}
}
因此它输出:
./src/main/java/Kata.java:8: error: method collect in interface DoubleStream cannot be applied to given types;
.collect(Collectors.groupingBy(n -> n,Collectors.counting()));
^
required: Supplier<R>,ObjDoubleConsumer<R>,BiConsumer<R,R>
found: Collector<Object,CAP#1,Map<Object,Long>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
where R is a type-variable:
R extends Object declared in method <R>collect(Supplier<R>,R>)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
./src/main/java/Kata.java:10: error: cannot find symbol
System.out.println("Map: "+map);
^
symbol: variable map
location: class Kata
2 errors
我想解决这个问题的方法是了解:
required: Supplier<R>,Long>>
我确实知道它期望:Supplier<R>,R>
,而我正在写:Collector<Object,Long>>
,但这意味着什么?我们该如何解决?为什么会生成?
然后我尝试了第二种方法:使用HashSet获取所有唯一的double,然后删除非唯一的double,然后返回唯一的double(存储在HashSet中)。
import java.util.*;
import java.util.stream.*;
public class Kata {
public static double findUniq(double arr[]) {
System.out.println("\nOriginal array: "+Arrays.toString(arr));
Set<Double> unique = new HashSet<Double>();
double repeated = Double.MIN_VALUE;
for(int i = 0; i < arr.length; i++){
if(repeated != arr[i] && !unique.add(arr[i])){
repeated = arr[i];
}
}
unique.remove(repeated);
System.out.println("Set: "+Arrays.toString(unique.toArray()));
return (double)unique.toArray()[0];
}
}
我的问题是,如何使用第一种方法返回唯一元素,并通过映射计数频率,然后返回值为1‽的键。
我也读过:
Java Hashmap: How to get key from value? How to get unique items from an array?