【问题标题】:Searching in a hash map在哈希映射中搜索
【发布时间】:2022-01-10 10:45:05
【问题描述】:

我想知道以下代码的时间复杂度是否为 O(n)(平均时间或编码面试的上下文):

for i in len(range(ls)):

   Dict = {}
   ......
   define foo
   if foo not in Dict.keys():
       Dict[foo] = 0

【问题讨论】:

  • 在 Python 3 上是 O(n),在 Python 2 上是 O(n**2)(其中 .keys() 返回一个 list,它们是 O(n) 来进行遏制测试,而不是 O(1) dict)。删除.keys(),两者都是O(n)

标签: python dictionary hash hashmap


【解决方案1】:

在 python 2 中它是 O(n),因为 keys() 返回一个列表。 在 Python 3 中是 O(1),因为 keys() 返回一个 KeysView 对象,该对象继承自 Set,见https://python.readthedocs.io/en/v2.7.2/library/collections.html#collections.KeysView

【讨论】:

    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2016-08-04
    相关资源
    最近更新 更多