微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

图的邻接表实现中移除顶点方法的时间复杂度

如何解决图的邻接表实现中移除顶点方法的时间复杂度

我正在尝试使用邻接列表(带有哈希映射容器)来实现图形数据结构。我知道有多种方法可以使用不同的数据结构来实现这一点,但我只是想将 GraphVertex 类和 Graph 类分开,以便以后可以轻松地将其转换为加权图和/或什至有向图。代码如下:

class GraphVertex {
  constructor(val) {
    this.val = val;
    this.edges = {};
  }
}

class Graph {
  constructor() {
    this.vertices = {};
  }

  // O(1)
  addVertex(vertex) {
    if (!this.vertices[vertex]) this.vertices[vertex] = new GraphVertex(vertex);
  }

  // O(1)
  addEdge(vertexOne,vertexTwo) {
    this.vertices[vertexOne].edges[vertexTwo] = true;
    this.vertices[vertexTwo].edges[vertexOne] = true;
  }

  // O(V) ???
  removeVertex(targetVertex) {
    delete this.vertices[targetVertex];
    const verticesArr = Object.keys(this.vertices);
    for (let i = 0; i < verticesArr.length; i++) {
      const vertex = verticesArr[i];
      if (this.vertices[vertex].edges[targetVertex]) {
        delete this.vertices[vertex].edges[targetVertex];
      }
    }
  }

  // O(1)
  removeEdge(vertexOne,vertexTwo) {
    delete this.vertices[vertexOne].edges[vertexTwo];
    delete this.vertices[vertexTwo].edges[vertexOne];
  }
}

我试图了解某些方法的时间复杂性。我一直读到删除列表的顶点将是 O(V + E) 但是然后我读到如果你使用哈希表它可能是 O(E)。但是看看我的代码,时间复杂度实际上是 O(V)。我是否正确解释了代码的 Big-O?还是我写的方法正确?

任何澄清将不胜感激。谢谢。

解决方法

您正在遍历 removeVertex 函数中的顶点列表,因此复杂度为 O(V)(它随顶点数线性增长)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。