python - 为什么这个脚本的运行时间是 O(n^2)?

标签 python algorithm big-o

我正在阅读 McDowell 的“Cracking the Coding Interview”,我对其中一个算法有疑问(它是第 6 版第 69 页的最后一个程序)。我在下面用 Python 写了出来。它应该找到 a^2+b^2=c^2+d^2 的时间,因为 a、b、c、d 是从 1 到 1000 的整数。显然它在 O(n^2) 时间内运行。我知道双循环是 O(n^2),但我不知道如何分析后面的三重循环。显然它是 O(n^2) 或更少,但我不知道为什么。

# This algorithm solves the above problem by making a 
# key for every unique a^2+b^2 sum... then the value for each key is
# a list of a,b tuples that I append to every time there is another a,b 
# with a given a^2+b^2 sum.
# Note that since a,b,c,d each on their own can take on any value 
# from 1 to 1000, we don't ever have to create the c^2+d^2 values
# since they will be the same as the a^2+b^2 values (the triple loop
# takes care of that idea).

sum_pair_dict = {}

n = 1001
for a in range(1,n):
    for b in range(1, n):
        sum = a**2 + b**2
        if sum in sum_pair_dict:
            sum_pair_dict[sum].append((a,b))
        else:
            sum_pair_dict[sum] = [(a,b)]

for a_sum, pair_list in sum_pair_dict.items():
    for pair1 in pair_list:
        for pair2 in pair_list:
            print(pair1, pair2)

最佳答案

  • 实际算法包含在仅前 2 个 for 循环中。这会进行真正的处理(求解方程)

  • 虽然确实第二个 3 个嵌套 for 循环 在 O(n^3) 中运行,但它们仅用于打印结果,实际上并没有做任何处理

关于python - 为什么这个脚本的运行时间是 O(n^2)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54534763/

相关文章:

java - 将 XML 转换为其他格式?

python - Django 。如何发表评论? - 最简单的例子。 CSRF验证失败

algorithm - 设计一种算法来查找 d 正则图中简单循环的长度

java - 分析希尔排序算法(大O)

Python 括号子字符串不起作用,为什么?

c# - 根据达到 1 所需的 Collat​​z 猜想循环次数找到一个数字

algorithm - 包含所有给定元素的最小数量的容器

python - 在 Python 中运行 munkres 库的复杂性

algorithm - 这些谜题的运行时间是多少?

python - 如何汇总每行时间前 1 小时到后 1 小时的价格,Pandas