问题描述
在以深度优先搜索方式遍历时,如果存在非常量操作,时间复杂度是多少?
例如,node[child]
是 set<int>
,因此 erase()
的运行时间为 O(log n)
,其中 n
是顶点数。
while(!q.empty()) { // O(n)
auto parent = q.front();
q.pop_front();
for(auto& child : node[parent]) { // O(e * log n)
if(!isVisited[child]) {
isVisited[child] = true;
q.push_front(child);
node[child].erase(parent); // O(log n)
} else {
return false;
}
}
}
那么总运行时间会是 O(n + e * log n)
,其中 e
是边的数量吗?
问题来自https://leetcode.com/problems/graph-valid-tree
更新:这是已接受的提交 https://leetcode.com/submissions/detail/518475470/
解决方法
假设这是一个连通图,是的,正如您推测大 O 表示法的整体复杂性
O (E logN)
对于边和顶点的集合,习惯上使用E和V。例如 ei 是针对特定边的。 |E|用于边数,但在上下文中可以使用 E 代替 |E|。