【问题标题】:How to implement a check member method in constant time O(1) for a queue list?如何在恒定时间 O(1) 中为队列列表实现检查成员方法?
【发布时间】:2017-09-26 12:04:15
【问题描述】:

我想在python中为队列列表(自我实现)实现一个检查成员方法,而不需要遍历所有成员来检查并且不牺牲顺序。

我有以下 FIFOqueue 实现:

class FIFOqueue(object):
 """Initialize with a list"""
def __init__(self, elements):
    self.list = elements

def pop(self):
     """Return the oldest element of the list (last index)"""
    return self.list.pop()

def insert(self, element):
     """Insert a new element at the end"""
    self.list = self.list + [element]

如何在上面的类中添加一个常数时间 O(1) 的检查成员方法?

【问题讨论】:

  • 你不能;这就是dicts 存在的原因。

标签: python list data-structures queue


【解决方案1】:

如果您想保持 O(1) 复杂度,请不要使用列表,更喜欢 dict,尤其是 OrderedDict in python 2X 以保持插入顺序,或者 python 3.6+ 的标准 dict(现在保持插入顺序)。

Here you can find time complexity 用于python中对象的标准操作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2017-09-29
    • 2011-10-12
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多