Home首页 / Lesson 1: Array第 1 课:数组
Lesson 1 · Data structure第 1 课 · 数据结构
What is an array?什么是数组?
A row of boxes with numbers. If you know the number, you jump straight to the box.一排带编号的盒子。知道编号,就能一步走到那一格。
01The idea先有一个画面
An array is that row of boxes. It has two facts:数组就是这一排盒子。它只有两个事实:
- The boxes are next to each other in memory.这些盒子在内存里紧挨着。
- Each box has a number, called an index. The first index is 0, not 1.每个盒子有个编号,叫 index(下标)。第一个是 0,不是 1。
| index下标 | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| value值 | apple苹果 | banana香蕉 | cherry樱桃 | date枣 | fig无花果 |
02Why reading is fast为什么“读”很快
Because the boxes touch each other, the computer can compute the address:因为盒子紧挨着,电脑可以直接算出地址:
address = start + index × size_of_one_box
So reading box 500 costs the same as reading box 0. One step. In Big O words, this is O(1) — constant time.所以读第 500 格和读第 0 格一样快:都是一步。用大 O 的说法,这叫 O(1),常数时间。
03Why inserting is slow为什么“插入”很慢
The boxes are full and touching. If you insert an item in the middle, every item after it must move one step to the right. With one thousand items, that is one thousand moves. This is O(n) — linear time.盒子是满的、紧挨着的。在中间插入一个东西,后面的每一个都得往右挪一步。一千个元素就是一千次挪动。这叫 O(n),线性时间。
When you add to the end and there is still room, it is O(1). Only inserting in the middle or at the front is expensive.往末尾加、并且还有空位,是 O(1)。只有往中间或最前面插才贵。
04Where you meet it你会在哪里遇到它
- A list of orders for today: you know the position, you want it fast.今天的订单列表:知道位置,要快。
- A HashMap is built on an array — that is why lesson 4 exists.HashMap 底层就是一个数组,所以后面要学第 4 课。
→New words新词
Click ▶ hear it for real people on YouGlish; 🔊 for the computer voice.点 ▶ hear it 听真人发音(YouGlish);点 🔊 听电脑朗读。
✓Check yourself自测
- Why is reading index 500 as fast as index 0?为什么读第 500 格和读第 0 格一样快?
- What has to happen when you insert in the middle?往中间插入时,发生了什么?
- Which is O(1) and which is O(n): read, insert at the end, insert at the front?哪个是 O(1)、哪个是 O(n):读、末尾加、最前面插?
Answer out loud first. Only then open the answers below.先自己出声答,再看下面的答案。