本文介绍了线性时间二次时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,一些答案提到给定的解决方案是线性,或者另一个是二次的.

Often, some of the answers mention that a given solution is linear, or that another one is quadratic.

如何发挥作用/识别什么?

How to make the difference / identify what is what?

有人能为像我这样仍然不认识的人解释这种最简单的方法吗?

Can someone explain this, the easiest possible way, for the ones like me who still don't know?

推荐答案

当方法花费的时间随着所涉及元素的数量线性增加而线性化.例如,用于打印数组元素的for循环大致是线性的:

A method is linear when the time it takes increases linearly with the number of elements involved. For example, a for loop which prints the elements of an array is roughly linear:

for x in range(10):
    print x

因为如果我们打印range(100)而不是range(10),则运行它所需的时间要长10倍.您会经常看到它写为O(N),这意味着运行该算法的时间或计算工作量与N成正比.

because if we print range(100) instead of range(10), the time it will take to run it is 10 times longer. You will see very often that written as O(N), meaning that the time or computational effort to run the algorithm is proportional to N.

现在,假设我们要打印两个for循环的元素:

Now, let's say we want to print the elements of two for loops:

for x in range(10):
    for y in range(10):
        print x, y

对于每个x,我循环10次y.因此,整个过程要经过10x10 = 100个打印(您可以通过运行代码来查看它们).如果不是使用10,而是使用100,那么该方法将执行100x100 = 10000.换句话说,该方法采用O(N * N)或O(N²)的形式,因为每次您增加元素数量时,计算工作量或时间将随点数的平方增加.

For every x, I go 10 times looping y. For this reason, the whole thing goes through 10x10=100 prints (you can see them just by running the code). If instead of using 10, I use 100, now the method will do 100x100=10000. In other words, the method goes as O(N*N) or O(N²), because every time you increase the number of elements, the computation effort or time will increase as the square of the number of points.

这篇关于线性时间二次时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 21:47