Python 设置转换的列表的时间复杂度是多少?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34642155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is time complexity of a list to set conversion?
提问by lxuechen
I've noticed the table of the time complexity of set operations on the python official website. But i just wanna ask what's the time complexity of converting a list to a set, for instance,
我注意到python官网上的set操作的时间复杂度表。但我只想问问将列表转换为集合的时间复杂度是多少,例如,
l = [1, 2, 3, 4, 5]
s = set(l)
I kind of know that this is actually a hash table, but how exactly does it work? Is it O(n) then?
我知道这实际上是一个哈希表,但它究竟是如何工作的?那么是 O(n) 吗?
采纳答案by Mad Physicist
Yes. Iterating over a list is O(n)
and adding each element to the hash set is O(1)
, so the total operation is O(n)
.
是的。遍历列表 isO(n)
并将每个元素添加到哈希集 is O(1)
,因此总操作是O(n)
。