【问题标题】:What is the time complexity of converting a set of n integers to a list of n integers?将一组 n 个整数转换为 n 个整数列表的时间复杂度是多少?
【发布时间】:2020-06-13 06:57:02
【问题描述】:
my_set = {1,2,3,4}
my_list = list(my_set)

这需要 O(n) 还是 O(1)

【问题讨论】:

  • my_set 没有以任何方式改变,my_list 是一个包含n 项目的全新对象。我不明白你为什么认为它可能是 O(1)。

标签: python python-3.x list set time-complexity


【解决方案1】:

根据下面的结果,my_list = list(my_set)这一行显然是O(n)

my_set = {1,2}
%timeit my_list = list(my_set)
my_set = {1,2,3,4,5,6,7,8,9,10}
%timeit my_list = list(my_set)
my_set = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
%timeit my_list = list(my_set)

输出:

403 ns ± 5.07 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
621 ns ± 77.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
905 ns ± 27.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多