Time Complexity of “in” (containment operator)

南楼画角 提交于 2019-12-31 02:40:46

问题


I was just wondering when understanding the time complexity of an algorithm like the one below.

For a python list, if we have a for loop iterating over it, and then a containment check, would the time complexity of that be O(n^2).

I know both are O(n) (or I think) so having them nested in one another would that make it O(n^2)?

I think if this "list" is actually a list, then the time complexity of the code below is O(n^2). But if it's a dictionary it would be O(n) because lookup is O(1). Is that correct?

Thanks for any help in advance!

for element in list:
    if x in list:

回答1:


Your analysis is correct.

  • List containment is O(n), and doing an O(n) operation O(n) times is O(n2).
  • Dictionary lookups are O(1), and doing an O(1) operation O(n) times is O(n).


来源:https://stackoverflow.com/questions/56419144/time-complexity-of-in-containment-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!