【发布时间】:2017-01-15 18:37:12
【问题描述】:
在 Python 中,我们知道在字典中查找键需要 O(1) 的运行时间,但是在 dictionary.values() 中查找的运行时间是多少?
dictionary = {'a':[66,77,88], 'b':[99,100]}
key = 'a'
if key in dictionary: # takes O(1) run time
number = '99'
if number in dictionary.values(): # What is the run time here?
编辑#1:键的值可以是列表或集合。许多人已经回答说,如果值是列表,则运行时间是 O(1)。
如果值是集合,会是 O(N) 吗?
dictionary = {'a':(66,77,88), 'b':(99,100)}
number = '99'
if number in dictionary.values(): # What is the run time here?
【问题讨论】:
-
O(n)当然,在最坏的情况下,您必须查看每个值。如果使用 python2 仅调用.values()会创建所有值的列表。 -
O(n)。它已读取所有值并与每个值进行比较。顺便说一句,如果您将列表作为值,它将不会那样工作。
-
基本上是
O(n)。但是,如果您想在列表中查找此类值,它将不再是 O(n)。 -
通常是 O(n),因为它只是通过一个列表
-
你在 2 天前还问了一个问题,它给了你所有 python 操作的复杂性stackoverflow.com/questions/39338520/…
标签: python performance dictionary hashmap big-o