大o表示法描述复杂度_如何使用大O表示法计算时间复杂度

本文深入探讨了大O表示法在描述算法时间复杂度中的应用,通过实例解析如何使用大O表示法来分析和计算算法的时间效率。内容来源于对一篇关于大o表示法的中英文翻译。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大o表示法描述复杂度

Part 2 of a series breaking down Big O Notation and Time and Space Complexity for new developers.

该系列的第2部分为新开发人员分解了Big O表示法和时间和空间复杂性。

If you’re on your way to becoming a software developer, you’ve most likely come across the terms ‘ Time and Space Complexity’ or ‘Big O Notation.’ If you haven’t, check out my quick primer on what Big O Notation is and why it should be on your radar.

如果您要成为一名软件开发人员,则很可能会遇到“时间和空间复杂性”或“大O符号”这一术语。 如果您还没有,请查看我的快速入门 ,了解什么是Big O注释以及为什么它应该出现在您的雷达上。

Knowing how to talk about Time and Space Complexity is crucial in any budding developer’s career. First of all, this subject is known to come up in coding interviews frequently, so it’s essential to familiarize yourself with the base concepts. More importantly, though, a strong understanding of how to calculate and discuss Time and Space Complexity is going to make you a better developer by making you aware of differences in terms of efficiency and provide you with the insight to develop better solutions for problems you work on.

在任何崭露头角的开发人员的职业生涯中,知道如何谈论时间和空间复杂性都是至关重要的。 首先,众所周知,该主题经常在编程访谈中出现,因此必须熟悉基本概念。 不过,更重要的是,对如何计算和讨论时间和空间复杂性的深刻理解将使您了解效率方面的差异,并为您提供解决问题的更好的解决方案的知识,从而使您成为一名更好的开发人员上。

Big O Notation is the vocabulary through which we discuss and understand these principles. Hence, we need to know how to calculate Big O in the context of both space and time to unlock the ability to write the best code possible. In the scope of this article, we’ll only discuss how to calculate Big O in the case of understanding Time Complexity.

大O符号是我们讨论和理解这些原理的词汇。 因此,我们需要知道如何在空间和时间的背景下计算Big O,以释放编写最佳代码的能力。 在本文的范围内,我们将仅讨论在了解时间复杂度的情况下如何计算BigO。

如何计算大O —基础 (How To Calculate Big O — The Basics)

In terms of Time Complexity, Big O Notation is used to quantify how quickly runtime will grow when an algorithm (or function) runs based on the size of its input.

就时间复杂度而言,大O表示法用于根据算法(或函数)的输入大小来量化运行时增长的速度。

To calculate Big O, there are five steps you should follow:

要计算Big O,您应该遵循五个步骤:

  1. Break your algorithm/function into individual operations

    将算法/功能分解为单独的操作
  2. Calculate the Big O of each operation

    计算每个操作的大O
  3. Add up the Big O of each operation together

    将每个操作的大O加起来
  4. Remove the constants

    删除常量
  5. Find the highest order term — this will be what we consider the Big O of our algorithm/function

    找到最高阶项-这就是我们认为算法/函数的大O

With that in mind, let’s start small and calculate the Big O of a simple function.

考虑到这一点,让我们从小处开始,并计算一个简单函数的BigO。

Take the following JavaScript code as an example:

以以下JavaScript代码为例:

function add(num1, num2) {

let total = num1 + num2;
return total;};

Pretty simple, right? We’re just adding two numbers together.

很简单,对吧? 我们只是将两个数字加在一起。

So let’s break this function down to evaluate each operation. Our example is made up of 4 separate operations:

因此,让我们分解一下此函数以评估每个操作。 我们的示例由4个单独的操作组成:

  1. Looking up num1

    查找num1

  2. Looking up num2

    查找num2

  3. Assigning the sum of the two numbers to the variable total

    将两个数字的和分配给变量total

  4. Returning total.

    返回total

Now that we’ve identified our operations let’s calculate the Big O for each of them. In this example, we’re dealing with pretty simple operations — each of which has a time complexity of O(1).

既然我们已经确定了操作,就可以为每个操作计算BigO。 在此示例中,我们处理的是非常简单的操作-每个操作的时间复杂度均为O(1)。

Their time complexity is O(1) or constant time because the operations only happen once, and they do not depend on the size of the input as they run.

它们的时间复杂度为O(1)或恒定时间,因为操作仅发生一次,并且它们在运行时不依赖于输入的大小。

Another way to think about this is that these operations will take the same amount of time to run, no matter what the inputs are. Running add(1,2) is going to take the same amount of time as add(10436,4783474).

考虑这种情况的另一种方法是,无论输入什么内容,这些操作都将花费相同的时间来运行。 运行add(1,2)将花费与add(10436,4783474)相同的时间。

Moving onto our next step, now that we know the Big O of each of our operations, let’s add it all together.

进入下一步,现在我们知道每个操作的大目标,让我们将它们加在一起。

Since each of our operations has a runtime of O(1), the Big O of our algorithm is O(1 + 1 + 1 + 1) = O(4), which we will then simplify to O(1) as we strip our constants and identify our highest-order term.

由于我们每个操作的运行时间均为O(1),因此算法的Big O为O(1 + 1 +1 + 1)= O(4),然后在剥离时将其简化为O(1)我们的常数,并确定我们的最高阶项。

But wait, how did we get 1 from 4? Think about what stripping out constants means. We want to boil Big O down to its most crucial element — its highest-order term. In this case, 4 is fluff. O(4) is essentially just saying O(4x1). Therefore, we’re just going to throw the four out and say the Big O for this algorithm is O(1), which indicates that it runs at constant time.

但是等等,我们如何从4中得到1? 想一想剥离常数的含义。 我们想将Big O归结为最关键的要素-最高阶。 在这种情况下,4是绒毛。 O(4)本质上只是说O(4x1)。 因此,我们将把这四个扔掉,并说此算法的Big O为O(1),这表明它在恒定时间运行。

This might seem confusing, but remember, at the end of the day, all we care about is getting a high-level sense of how an algorithm will perform in the worst case. Therefore, we simplify Big O notation as much as we can to achieve that goal.

这似乎令人困惑,但是请记住,归根结底,我们关心的只是对算法在最坏情况下的性能有一个高级了解 因此,我们尽可能地简化Big O表示法以实现该目标。

常见的Big O函数以及如何识别它们 (Common Big O Functions and How to Identify Them)

So, now that you have your step-by-step guide on how to calculate Big O Notation let’s review some common Big O functions that you’ll run into in the wild and discuss how you can identify them.

因此,既然您有了有关如何计算Big O表示法的分步指南,让我们回顾一下您将在野外遇到的一些常见Big O函数,并讨论如何识别它们。

Constant Time: O(1)

恒定时间:O(1)

As we discussed earlier, algorithms or operations are considered to have a constant time complexity when they are not dependent on the size of the input data, and the time required to run is the same every single time.

如前所述,算法或运算不依赖于输入数据的大小而被认为具有恒定的时间复杂度,并且每次运行所需的时间相同。

Addition, subtraction, assignment, and most forms of basic lookup all are considered to run at constant time, so when you see these types of operations, make a quick mental note that they run at O(1).

加法,减法,赋值和大多数形式的基本查找都被认为是恒定时间运行的,因此,当您看到这些类型的操作时,请快速记住它们在O(1)处运行。

Linear Time: O(n)

线性时间:O(n)

Here comes the algebra. Algorithms or operations that have a linear time complexity can be identified by the fact that the number of operations increases linearly with the size of the input.

代数来了。 具有线性时间复杂度的算法或运算可以通过以下事实来识别:运算数量输入大小线性增加。

That means if an operation has to run 100 times for a list that’s 100 items long, then it has linear time complexity.

这意味着,如果一个操作必须运行100次才能运行100个项目的列表,则它具有线性时间复杂度。

for loops are a great example of an operation that has linear time complexity. Let’s look at an example:

for循环是具有线性时间复杂度的运算的一个很好的例子。 让我们看一个例子:

for (let i = 0; i < exampleArray.length; i++) {
console.log(`I've done this ${i} times before!`);
}

In the above example, if exampleArray is only 1 item long, our algorithm is going to run pretty fast. But what if that array is increased in size by, oh I don’t know, 500 million values? It’s going to take a lot longer for this algorithm to run. Therefore, we define this algorithm as having a linear time complexity to indicate that as the size of the input grows, the amount of time needed to run it increases accordingly.

在上面的示例中,如果exampleArray只有1个项目,则我们的算法将运行得非常快。 但是,如果该数组的大小增加5亿(不知道),该怎么办? 该算法运行将需要更长的时间。 因此,我们将此算法定义为具有线性时间复杂度,以表明随着输入大小的增长,运行它所需的时间也相应增加。

Other examples of operations that have linear time complexity are .shift() or .unshift(), which highlights another important point:

具有线性时间复杂度的运算的其他示例是.shift().unshift() ,这突出了另一个重要点:

When you calculate the time complexity of an algorithm, native methods have their own time complexity as well.

在计算算法的时间复杂度时,本机方法也具有其自身的时间复杂度。

I won’t go into this further at the moment, but just be sure to note that just because a method is native to the language you are programming in, it is not guaranteed to have a constant time complexity. If you’re ever unsure, just give it a Google to find your answer.

目前,我将不做进一步介绍,但是请务必注意,仅因为方法是您正在使用的编程语言所固有的,就不能保证它具有恒定的时间复杂度。 如果您不确定,请给它一个Google来找到您的答案。

Quadratic Time: O(n²)

二次时间:O(n²)

Algorithms or operations that have quadratic time are identified as having to perform a linear time operation for each value in an input, not just for the input itself.

具有二次时间的算法或运算被标识为必须对输入中的每个值执行线性时间运算,而不仅仅是对输入本身执行线性时间运算。

Nested loops are a simple example of this concept:

嵌套循环是此概念的一个简单示例:

for (let i = 0; i < exampleArray.length; i++) {for (let y = 0; y < exampleArray.length; y++) {console.log(`I said ${exampleArray[i]} ${y} times!`);
}
}

As you can see, the runtime of our algorithm compounds as we have to reference each item in our input twice. Therefore, we multiply the dependencies against each other (O(n*n)) to arrive at O(n²) time complexity. The same logic continues to apply if you keep nesting more loops, so runtimes of O(n³) or O(n⁴) are entirely possible.

如您所见,我们的算法的运行时间很复杂,因为我们必须两次在输入中引用每个项。 因此,我们将相互之间的依赖关系相乘(O(n * n)),得出O(n²)的时间复杂度。 如果您继续嵌套更多的循环,则继续使用相同的逻辑,因此O(n³)或O(n⁴)的运行时间是完全可能的。

结论 (Conclusion)

This is hardly a conclusive summary of all Big O functions that you will encounter, as other common Big O functions include Logarithmic Time, Exponential Time, Factorial Time, and more.

这几乎不是您将遇到的所有Big O函数的结论性总结,因为其他常见的Big O函数包括对数时间,指数时间,阶乘时间等。

With that being said, you now have a framework to start calculating the time complexity of your algorithms and the amount of knowledge necessary to start coding more efficient solutions.

话虽如此,您现在有了一个框架来开始计算算法的时间复杂度以及开始编写更有效的解决方案所需的知识量。

I’ll also be continuing this series with a break down of how to evaluate Space Complexity soon.

我还将在本系列的后续部分继续介绍如何快速评估空间复杂性。

翻译自: https://medium.com/dataseries/how-to-calculate-time-complexity-with-big-o-notation-9afe33aa4c46

大o表示法描述复杂度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值