【发布时间】:2013-09-22 07:54:40
【问题描述】:
当我开始将图形实现为邻接列表时,我注意到 检查 v1 是否与 v2 相邻的运行时间为 O(V)
bool isAdjacent(int v1, int v2){
for(int i = 0; i < V; ++i){
if(this.graph[v1][i] == v2){ return true; }
}
return false;
}
循环一直工作到 V(顶点数),所以它是 O(V)
我可以使用 HashSet 代替 ArrayList 或 vector 吗?
原来是ArrayList< ArrayList<Integer> > graph;
或Vector< Vector<Integer> > graph;
现在我想知道为什么我们不能创建
ArrayList
这将使 bool isAdjacent(int v1, int v2); O(1) 因为在 HashSet 中搜索的顺序是 O(1)?
如果 hashset 不能使用,因为它比需要的内存要多,那么二叉树呢? ?
ArrayList
在这种情况下,搜索 O(lg V) 比 O(V) 好
谁能帮忙,为什么之前没有创建这个实现??
【问题讨论】:
标签: graph binary-search-tree hashset