Java Notes

Home首页 / Lesson 5: Big O第 5 课:复杂度

Lesson 5 · Complexity第 5 课 · 复杂度

What is O(1), O(n), O(log n)?什么是 O(1)、O(n)、O(log n)?

Big O is not about seconds. It is about how the cost grows when the data grows.大 O 说的不是几秒,而是“数据变多时,代价怎么变”。

Short answer先给答案Big O is not seconds; it is how the number of steps grows when the data grows. O(1) one step · O(log n) halve each time · O(n) one by one · O(n²) every pair.大 O 说的不是几秒,而是“数据变多时步数怎么长”:O(1) 一步;O(log n) 每次砍一半;O(n) 一个一个来;O(n²) 两两配对。

Basics基础complexity复杂度must know必背

01The idea先有一个画面

Think of it like this先这样想Finding a shoe. (1) You know the box number — open one box. (2) The boxes have no order — open one by one. (3) The boxes are sorted by size — cut the range in half each time.找鞋:(1) 你知道在哪一格——开一格; (2) 全乱堆着——一格一格开; (3) 按大小排好了——每次砍一半。

That is O(1), O(n), O(log n). The letter is the data size; the function is how many steps you need.这就是 O(1)、O(n)、O(log n)。字母是数据量,函数是需要的步数。

Big O大 OMeans意思n=1000 steps1000 个时要几步
O(1)one step, no matter how many不管多少,都是一步1
O(log n)half each time每次砍一半about 10约 10
O(n)one by one一个一个来1000
O(n log n)sort by halving, n times每次砍一半、做 n 遍about 10000约 1 万
O(n²)every pair两两配对1,000,000100 万

02How to read it怎么读出来

“O” is said “big O”. “O(1)” is “big O of one, constant time”. “O(log n)” is “big O of log n”.“O”读作 big O;“O(1)”读 big O of one,也叫常数时间;“O(log n)”读 big O of log n。

We drop the small parts. O(2n + 5) is O(n); O(n² + n) is O(n²). Big O cares about the shape of the curve, not the exact number.小项会被丢掉:O(2n + 5) 就是 O(n),O(n² + n) 就是 O(n²)。大 O 只看曲线的形状,不看具体数字。

03Where you meet it你会在哪里遇到它

In an interview, say the number and why: “O(1), because it computes the bucket from the hash.”面试时说数字,并且说原因:“O(1),因为它是用 hash 直接算出桶的位置。”

→New words新词

time complexity /taɪm kəmˈpleksəti/ How run time grows with data size.时间复杂度:耗时随数据量增长的方式 ▶ hear it
Big O /bɪɡ oʊ/ The notation for that growth.大 O:描述增长的量级记号 ▶ hear it
constant /ˈkɑːnstənt/ Does not grow: O(1).常数:不增长,O(1) ▶ hear it
linear /ˈlɪniər/ Grows in a line: O(n).线性:成一条直线增长,O(n) ▶ hear it
logarithmic /ˌlɔːɡəˈrɪðmɪk/ Grows very slowly: O(log n).对数:增长很慢,O(log n) ▶ hear it

Click ▶ hear it for real people on YouGlish; 🔊 for the computer voice.点 ▶ hear it 听真人发音(YouGlish);点 🔊 听电脑朗读。

✓Check yourself自测

  1. In your own words: what is O(n)?用你自己的话说:什么是 O(n)?
  2. Why is reading an array O(1)?为什么读数组是 O(1)?
  3. A bucket with 8 items: how many steps at most?桶里有 8 个元素:最多几步?

Answer out loud first. Only then open the answers below.先自己出声答,再看下面的答案。

Answers参考答案
01Steps grow in a straight line with n: double the data, double the steps.步数和 n 成正比:数据翻倍,步数也翻倍。
02One multiplication and one addition give the address. No loop, no search.一次乘法加一次加法就算出地址,没有循环、没有查找。
03If the bucket has treeified: about 3 comparisons (log₂8). If it is still a list: at most 8.已经树化:约 3 次比较(log₂8);还是链表:最多 8 次。

Next: Lesson 6, HashMap methods →下一课:第 6 课,HashMap 方法 →