如何在队列列表的常量时间O(1)中实现检查成员方法?

时间:2017-09-26 12:04:15

标签: python list data-structures queue

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

我有以下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)中向上面的类添加一个检查成员方法?

1 个答案:

答案 0 :(得分:0)

如果你想保持O(1)的复杂性,不要使用list,首选dict,尤其是OrderedDict in python 2X来保持插入顺序,或者使用python 3.6+的标准dict(现在保持插入顺序)。

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