我有一些对象,每个对象都有一个唯一的 ID,这些对象被插入到各种列表中。这些对象需要经常从其相应列表的中间删除,通常是 O(n),所以我想将它们的位置保留在 dict 中并且每次我想删除它时,在 O(1) 中检索对象的位置。
class Node(object):
def __init__(self, lst_id, unique_id):
self.lst_id = lst_id
self.unique_id = unique_id
n1 = Node('a', 1)
n2 = Node('a', 2)
n3 = Node('b', 3)
node_lsts = {}
for node in [n1,n2,n3]:
if node.lst_id in node_lsts:
node_lsts[node.lst_id].append(node)
else:
node_lsts[node.lst_id] = [node]
nodes_hash = {n1.unique_id: n1, n2.unique_id: n2, n3.unique_id: n3}
ID_TO_REMOVE = 1
在上面的示例中,如果我简单地调用 del nodes_hash[ID_TO_REMOVE],node_lsts 中的相应对象将保留,即使它已从字典中删除 - 我应该如何获取它从 O(1) 的相应列表中删除?
在 C++ 中,我可以将指向邻居列表的指针保留为节点成员变量(链表),并通过其内存地址查找节点,获取指向其邻居的指针,取消该节点与其邻居的链接(从而将其从 ' list') 最后释放节点。我正在尝试复制此行为。
请您参考如下方法:
您可以在 Python 中轻松创建双向链表:
class DoublyLinkedListNode(object):
def __init__(self, unique_id, lst_id, left=None, right=None):
self.unique_id, self.lst_id = unique_id, lst_id
self.left = left
self.right = right
def remove(self):
if self.left is not None:
self.left.right = self.right
if self.right is not None:
self.right.left = self.left
self.left = None
self.right = None
def append(self, node):
node.left = self
node.right = self.right
if self.right is not None:
self.right.left = node
node.right = self.right
self.right = node
def prepend(self, node):
node.left = self.left
node.right = self
if self.left is not None:
self.left.right = node
self.left = node
def iter_left(self):
current = self
while current.left is not None:
yield current.left
current = current.left
def iter_right(self):
current = self
while current.right is not None:
yield current.right
current = current.right
作为链表,对于任何给定节点,这具有 O(1) 插入和删除操作。如果您可以通过字典或其他一些更适合的数据结构保留对每个节点的引用,这将允许您平均情况下 O(1) 访问和快速顺序迭代。
class ListContainer(object):
def __init__(self):
self.lists = {}
self.node_mapping = {}
def append(self, node):
if node.lst_id in self.lists:
self.lists[node.lst_id].append(node)
else:
self.lists[node.lst_id] = node
self.node_mapping[node.unique_id] = node
def remove(self, node):
...
请注意,如果您的列表中只有几百个元素,那么这一切都是白费力气。对于如此少的元素,纯 Python 数据结构可能不会比您的 Python 实现的列表数据结构更快。 Big-O 符号会忽略常数项,如果您没有处理足够多的元素(例如 Coppersmith-Winograd algorithm ),常数项可能会非常大。
