2016-11-26 80 views
1

是否有机会来优化下一行代码:列表性能优化

val adj: Array[ListBuffer[Int]] = Array.fill(n)(ListBuffer[Int]()) 
... 
.. 

val sourceVertexes = inGraph.zipWithIndex.filter(v => a.zipWithIndex.exists(r => r._2 != v._2 && r._1.exists(f => f == v._2)) 

inGraph - 阵列方向/链接到其他顶点顶点。例如,图形大小可以说是10000个顶点。

我想找到的源列表(从顶点列表中的任何在-边缘正在添加)

val adj: Array[List[Int]] = Array.fill(n)(List[Int]()) 
+0

第一行代码中的“a”是什么? – kraskevich

+0

刚更新的问题。我更怀疑我应该将数据类型从(List或ListBuffer)更改为不同的东西。 – Pavel

回答

2

是的,这是可以通过使用更高效的算法,使其更快。 现在做什么样的代码基本上是:

for each vertex: 
    for each edge: 
     if egde goes to vertex: 
      discard it 

它在最坏情况下的O(n * m)时间复杂度(其中m是边缘的数量和n是顶点的数量)。

这里是一个解决方案,它是在图中的尺寸线性:

noIncoming = a hash set with all vertices (or just a boolean array) 
for each edge: 
    if edge is not a loop: 
     noIncoming.remove(edge.desitination) // or we can put a mark in a boolean array 

noIncoming是一组与没有入边的顶点。

+0

谢谢,不知道它是这样工作的。不过,我决定去寻求其他解决方案。我创建了其他一系列列表来保留包含时间线的时间搜索列表。 – Pavel