COMPUTER SCIENCE · 74
Data Structures:同一份資料,用不同結構會讓操作成本完全不同
Array、Stack、Queue、Set、Map 不是「五個 API」。它們代表不同資料組織方式,也因此對 lookup、insert、delete、ordering、uniqueness 有不同 trade-off。選結構前先問:最常做的 operation 是什麼?
Learning outcomes
- 能依 operation 選 Array/Stack/Queue/Set/Map。
- 能說明 order、uniqueness、key lookup 等語意差異。
- 能區分 logical data structure 與語言內建 implementation。
- 能預測錯選結構造成的複雜度與可讀性問題。
1. Array:有順序、可索引、適合遍歷
const lessons = [
"Values",
"Functions",
"DOM"
];
lessons[1];
// "Functions"Array 適合 sequence。若你常做「依 id 找 item」,每次線性 scan 可能不是最佳選擇。
2. Stack:LIFO
push(A)
push(B)
pop() → B
pop() → ACall stack、undo history、DFS 都常用 stack model。重點是最後加入者先取出。
3. Queue:FIFO
enqueue(A)
enqueue(B)
dequeue() → A
dequeue() → BJob queue、request queue、BFS 等情境通常更接近 first-in-first-out。
4. Set:唯一集合
const tags =
new Set();
tags.add("js");
tags.add("js");
tags.size;
// 1Set 很適合 membership / uniqueness;但如果你需要 key → value,就更像 Map。
5. Map:key → value lookup
const byId =
new Map();
byId.set(
101,
{ title: "JavaScript" }
);
byId.get(101);Map 把「找某個 key 的 value」變成核心 operation。
Project checkpoint:Course Index
同一份 lessons 同時建立 Array 與 Map index:Array 保留排序,Map 提供 id lookup。
const lessons = [...];
const byId =
new Map(
lessons.map(
lesson => [
lesson.id,
lesson
]
)
);Debug evidence:資料明明有,lookup 卻很慢
先問資料規模、lookup 次數、是否每次都 find() 整個 array。不要看到慢就先換 framework;資料結構可能才是瓶頸。
Knowledge check
- Undo history 比較像 Stack 還是 Queue?
- 需要去重 email 適合哪個結構?
- 需要依 lesson id 高頻 lookup,Array 與 Map 你會怎麼搭配?
- 替 BFS / DFS 各選一個核心資料結構。