2016-12-02 74 views

回答

1

计算您的数字值的散列值并计算重复散列值的数量。

的简单实现的,这可能是:

List<Integer> yourValues = /* Your set of numbers */; 
Map<Integer, Set<Integer>> map = new HashMap<>(); 
// Insert all elements into buckets based on their hash value 
yourValues.forEach(value -> { 
    if (!map.containsKey(value.hashCode())) 
     map.put(value.hashCode(), new HashSet<>()); 
    map.get(value.hashCode()).add(value); 
}); 
// Sum up the number of values in each bucket, subtract the number of buckets, so only duplicate values are counted 
int collisions = map.values().stream().map(Set::size).reduce(0, Integer::sum) - map.size(); 
System.out.printf("Number of collisions: %d\n", collisions); 
+0

谢谢你。但是,我对你的数据类型是什么有点困惑。你能澄清一下吗? – Name158

+0

它是整数值的集合。可能是列表或设置。我改变了答案。 – Palle