java - 基于实体等于的嵌套列表到唯一集
问题描述
我发现了我的 Kruskal 实现的瓶颈。我需要转换一个
List<List<Edge<T extends Comparable<T>>>> adjacencyList;
// This looks like this: get(0) = [Edge:{Vertex V0, Vertex V1, T weight}, Edge:{Vertex V0, Vertex V2, T weight}, ...]
// and get(indexOf(Vertex V1)) = [{Vertex V1, Vertex V0}, ...]
// obviously indexOf(Vertex) does not comply with type Edge, but the idea is that the index of the Edge where the Vertex otherFirst is the getFrom() is retrieved.
到一个唯一的边列表(参见 equals 方法以了解相等性)。我需要对此进行优化,并可能用更有效的解决方案替换。解决方案应如下所示:
get(0) = Edge:{Vertex V0, Vertex V1, T weight}
// there is no element which is Edge:{Vertex V1, Vertex V0, T weight}
我目前的解决方案如下所示:
private List<Edge<T>> toAdjacencyList(final List<List<Edge<T>>> edges) {
List<Edge<T>> flat = edges.parallelStream().flatMap(List::stream)
.collect(Collectors.toList());
final Set<Edge<T>> unique = new HashSet<>();
unique.addAll(flat);
return new ArrayList<>(unique);
}
- 针对 1000 个顶点、1000 个边输入运行此程序需要 5 毫秒。
- 针对 1000 个顶点、10000 个边输入运行此程序需要 780 毫秒。
- 针对 1000 个顶点,100 000 条边输入需要 X 秒。我不知道。(这就是我需要工作的)。
数据缓存后的实际 Kruskal 算法需要不到一秒的时间。
我该如何优化它,或者替换它?
注意:两条边相等意味着 Edge:{V1, V0, 10f} 和 Edge:{V0, V1, 10f} 相同。我很肯定这有效。
解决方案
我错误地实现了 equals 方法,但是,如果有人遇到类似问题,我忘记在 hashCode 中包含 Vertex from 和 Vertex to。
推荐阅读
- python - VS Code 中的“运行”按钮不显示 [Python]
- python-2.7 - 如何在 python 中从 docker 访问环境变量?
- php - 如何使用 PHP 将样式应用于段落
- nginx - 将 Kubernetes 集群公开到 Internet
- arrays - 摆脱空字符串列表
- swift - 声明许多常量?迅速
- swiftui - 在 Xcode 12(测试版)中使用实时预览时无法在 TextField 中输入文本
- wpf - 带有绑定的 Button.LostFocus 上的 WPF 触发器
- .net - 使用 SSH.NET 响应交互式 shell 提示
- nginx - X-Forwarded-Proto 标头作为 http 发送,即使在 nginx 中将值设置为 https