Top K Frequent Elements
工作主題Retrieval / Ranking · NLP / LLM
解題技術Hash Map · Bucket Sort
頻率排名的直接基礎;熱門 item / query 統計。
題目、例子與複習提示
題目整理
回傳陣列中出現次數最多的 k 個不同數字,結果順序不限。
nums=[4,4,1,1,1,9], k=2 → [1,4]
解法說明
先計數,再依頻率分桶,由高到低收集 k 個元素。
O(n)
O(n)
n 為輸入元素數。
28 題演算法練習,依九類工作主題整理。優先開啟 NeetCode 解題,搭配 LeetCode 與既有繁中筆記;每類再接到直接的 ML 實作。
以下依各平台公開頁面整理;題庫、學習路線與理論問答分開看。免費範圍、登入要求與內容供應以平台目前頁面為準。
| 資源 | 實際分類/內容 | 適合怎麼用 |
|---|---|---|
| ML Coding | Retrieval & Ranking、Metrics、Loss & Training、Data & Features、LLM Components、Debugging。 | 與這份工作主題相當接近;可直接練 BM25、NDCG、Attention、KV cache 等元件。 |
| TensorTonic · Roadmap | Loss、Activation、NLP、Linear Algebra、Transformers、Metrics & Evaluation;題庫也有 Value Iteration 與 Q-learning。 | 補模型訓練、RL 與數值實作;可跑測試,並有理論/解法分頁。 |
| Deep-ML | Linear Algebra、ML、Deep Learning、NLP、Computer Vision;另有 collections、labs 與 projects。 | 依技術能力練 Python / ML 元件,適合補 NeetCode 題單以外的實作。 |
| NeetCode Roadmap | 依演算法模式學習;官方 準備指南 也建議先掌握 patterns。 | 本頁演算法題的主要解題入口;再由本頁補上「這題與工作有什麼關聯」。 |
| Machine Learning 150 | 以 ML 概念與面試問答為主;查核時多個章節標示 Under Construction。 | 理論補充。不要把它當作 150 題可立即執行的 coding 題庫。 |
這題服務什麼問題?例如 retrieval 的候選選取、production 的 cache,或 evaluation 的串流統計。
這題怎麼解?例如 Heap、Binary Search、Graph、DP。一題可以跨工作主題,但只保留一份題目卡片。
各主題末尾有延伸資源。Training、RL、Causal、Safety 的完整能力,需要直接做模型、估計流程或評估程式。
| 工作主題 | 題數 | LC 覆蓋程度 | 下一步 |
|---|---|---|---|
| Retrieval / Ranking / Recommendation | 5 | 直接基礎較多 | 先練 Top K Frequent Elements → K Closest → Search Suggestions,再比較 Words 的 tie-break 與多路合併。 |
| NLP / LLM Applications | 5 | 字串處理基礎 | Encode/Decode → Word Break → Edit Distance;頻率三題可一起複習。 |
| Agentic Workflows / Planning | 3 | 依賴與搜尋基礎 | Course Schedule II → Combination Sum → Network Delay Time;再回看 LRU / TimeMap 的狀態管理。 |
| Model Training / Adaptation | 2 | LC 僅涵蓋周邊元件 | Random Pick with Weight → RandomizedSet;若面試要求 ML coding,優先接續 training step。 |
| Reinforcement Learning / Decision Making | 2 | DP 類比;需直接練 RL | 先能說明 DP 的 state/action/transition,再直接做 Value Iteration 與 Q-learning update。 |
| Evaluation / Experimentation / Causal Inference | 3 | 統計聚合基礎 | Range Sum → Median → Sliding Window Maximum;ASR / OCR 指標再看 Edit Distance。 |
| Production ML Systems / Efficiency | 3 | 系統元件直接基礎 | LRU Cache → TimeMap → Task Scheduler;再用 Median / Sliding Window 練監控資料處理。 |
| Multimodal / Computer Vision / Speech | 3 | 網格與序列基礎 | Flood Fill → Number of Islands → Rotate Image;語音評估看 Edit Distance,跨模態檢索看 K Closest。 |
| Safety / Robustness / Interpretability | 2 | LC 僅弱相關 | Valid Parentheses 可作為暖身;Regex 是選做。主要準備分群錯誤分析、對抗擾動與 attribution。 |
題目卡預設按主要主題排列;篩選會包含跨主題標籤。NeetCode 連到解題頁;已有的繁中說明可直接跳轉。16 題標為「起步題」,是本頁建議的學習起點。
沒有符合的題目。請清除篩選,或用「Heap」「字串」等其他關鍵字。
先把候選找出來,再依分數排序與選取。Top-K、prefix lookup 和多路合併都有清楚的演算法對應;個人化、learning to rank 與 offline metrics 仍需另外實作。
工作主題Retrieval / Ranking · NLP / LLM
解題技術Hash Map · Bucket Sort
頻率排名的直接基礎;熱門 item / query 統計。
回傳陣列中出現次數最多的 k 個不同數字,結果順序不限。
nums=[4,4,1,1,1,9], k=2 → [1,4]
先計數,再依頻率分桶,由高到低收集 k 個元素。
n 為輸入元素數。
可先複習 NeetCode:Top K Frequent Elements(相關題),再到本題既有詳解補字典序 tie-break。
工作主題Retrieval / Ranking · NLP / LLM
解題技術Hash Map · Sorting
詞頻榜加上穩定的字典序 tie-break。
回傳頻率最高的 k 個字,先按頻率降序,再按字典序升序。
words=["ml","ai","ml","ai","data"], k=2 → ["ai","ml"]
用 (-frequency, word) 排序;平手規則是本題與 Elements 的主要差異。
C 為所有輸入字元數,u 為不同單字數,L 為最長單字長度;字串比較最壞 O(L)。
工作主題Retrieval / Ranking · Multimodal / CV / Speech
解題技術Heap
練習依距離保留候選;二維原點距離是簡化模型,並非 ANN 索引。
回傳離原點最近的 k 個二維點,順序不限。
points=[[3,0],[1,1],[-1,0]], k=2 → [[-1,0],[1,1]]
維持最多 k 個點的 max-heap;平方距離即可比較遠近。
n 為點數。
工作主題Retrieval / Ranking · NLP / LLM
解題技術Sorting · Binary Search
直接對應 prefix autocomplete;排序規則是字典序,並非個人化分數。
每輸入一個字元,輸出最多三個符合當前 prefix、字典序最小的商品名。
products=["car","cat","cup"], searchWord="ca" → [["car","cat","cup"],["car","cat"]]
排序後,對各 prefix 用 lower_bound 找起點,只檢查接下來最多三個商品。
n 為商品數,L 為最長商品名,m 為查詢長度;計入 Python 排序空間與 prefix 字串,結果僅存字串參照。
工作主題Retrieval / Ranking · Production / Efficiency
解題技術Heap · Linked List
多路有序結果合併;可類比合併各 shard 的排序結果。
把 k 條已排序 linked lists 合成一條排序串列。
lists=[[1,4],[2,3],[0,5]] → [0,1,2,3,4,5]
Heap 只保存每條串列尚未輸出的最小節點;取出後補入該串列下一個。
N 為總節點數,k 為串列數;額外空間不含輸出。
字串題能練資料表示、解析與切分。Word Break 是字典切詞,Edit Distance 是字元編輯成本;兩者都能幫助理解 NLP 管線,但不涵蓋語意建模或 RAG 品質。
工作主題NLP / LLM · Training / Adaptation
解題技術Hash Map
練習以特徵 signature 分組;anagram 不表示語意相同,不能直接當語意去重。
把字母種類與次數完全相同的單字分為同組。
["tea","eat","tan"] → [["tea","eat"],["tan"]]
小寫英文可用 26 維頻率 tuple 當 key,避免反覆比較字串。
C 為總字元數,n 為單字數;字母表固定 26,輸出持有原字串參照。
工作主題NLP / LLM · Agents / Planning · Production / Efficiency
解題技術String Parsing · Design
練習可靠的文字序列化;內容含分隔符也必須可還原。
設計字串清單與單一字串之間可無損往返的 encode / decode。
["a#b",""] → "3#a#b0#" → ["a#b",""]
為每段寫入長度前綴;decode 讀完長度後,精確消耗該長度的內容。
C 為總字元數,n 為字串數;包含輸出與空字串的記錄成本。
工作主題NLP / LLM
解題技術Dynamic Programming
字典切詞的簡化模型;LLM 的 BPE 有不同的合併規則。
判斷字串能否完全拆成字典中的單字,字典中的字可重複使用。
s="aiml", dict=["ai","ml"] → true
dp[i] 表示前 i 個字元可切分;從可達位置嘗試匹配字典單字。
n 為字串長度,d 為字典大小,L 為最長單字;以逐詞 startswith 版本為準,不含輸入。
工作主題NLP / LLM · Evaluation / Causal · Multimodal / CV / Speech
解題技術Dynamic Programming
可延伸到 ASR 的 WER、OCR 的 CER;這題先處理字元級編輯次數。
用插入、刪除、替換,把 word1 變成 word2,回傳最少操作數。
word1="cat", word2="cut" → 1
每個 prefix pair 的最佳答案只依賴插入、刪除、替換的較短 prefix;相同字元不需付費。
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
previous = list(range(len(word2) + 1))
for i, ch1 in enumerate(word1, 1):
current = [i]
for j, ch2 in enumerate(word2, 1):
if ch1 == ch2:
current.append(previous[j - 1])
else:
current.append(1 + min(
previous[j], # Delete from word1.
current[j - 1], # Insert into word1.
previous[j - 1], # Replace.
))
previous = current
return previous[-1]
m、n 為兩字串長度;只保留上一列與目前列。
"cat" → "cut": replace a with u → 1
"" → "abc": insert a, b, c → 3中文:先定義兩個 prefix 的距離,再解釋三種操作各自對應哪個相鄰狀態。
工作主題NLP / LLM · Retrieval / Ranking
解題技術Hash Map · Sorting
與兩題 Top K 同屬 frequency counting;本題要輸出全部字元。
依出現次數由多至少重排全部字元;同頻率的字元順序不限。
s="tree" → "eetr"("eert" 也合法)
先計數,再按頻率排序不同字元,按次數重複寫回。
n 為字串長度,u 為不同字元數;計入輸出與暫存字串。
固定 workflow 可先用 graph 表示:依賴是否可完成、執行順序是否合法、搜尋成本是多少。真正 agent 的工具回傳、重試、動態規劃與記憶要再用小型系統練習。
工作主題Agents / Planning · Production / Efficiency
解題技術Graph · Topological Sort
固定依賴的 workflow 排序;真實 agent 還需處理動態任務和失敗。
給先修依賴,輸出可完成全部課程的順序;有 cycle 則回傳空清單。
numCourses=3, prerequisites=[[1,0],[2,1]] → [0,1,2]
Kahn:只執行入度為 0 的節點,完成後解除後續依賴;輸出不足代表 cycle。
V 為課程數,E 為依賴數。
工作主題Agents / Planning · Production / Efficiency
解題技術Graph · Heap
練習帶成本的 graph search;本題求所有節點收到訊號的最晚時間。
有非負邊權的有向圖,從 k 發送訊號,回傳所有節點收到的最短所需時間;有人不可達則 -1。
times=[[1,2,2],[2,3,1],[1,3,5]], n=3, k=1 → 3
Dijkstra 每次確認最小暫定距離;答案是所有最短距離的最大值。
from heapq import heappop, heappush
class Solution:
def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:
graph = [[] for _ in range(n + 1)]
for source, target, weight in times:
graph[source].append((target, weight))
distance = [float("inf")] * (n + 1)
distance[k] = 0
heap = [(0, k)]
while heap:
cost, node = heappop(heap)
if cost != distance[node]:
continue # Ignore a superseded candidate.
for neighbor, weight in graph[node]:
candidate = cost + weight
if candidate < distance[neighbor]:
distance[neighbor] = candidate
heappush(heap, (candidate, neighbor))
answer = max(distance[1:])
return -1 if answer == float("inf") else answer
以允許 heap 保留過期候選的實作為準。
1 → 2 costs 2; 2 → 3 costs 1; 1 → 3 costs 5
After node 1: distances = [0,2,5]
After node 2: distances = [0,2,3]
Return max = 3; the heap's old (5,3) entry is ignored.中文:區分每個節點的最短到達時間與所有節點都收到訊號的時間。
解題技術Backtracking
練習候選探索、限制檢查與撤銷選擇;用作 planning 的搜尋基礎。
從不同正整數中選數,可重複使用,列出總和等於 target 的不同組合;順序不產生新組合。
candidates=[2,3], target=6 → [[2,2,2],[3,3]]
固定候選 index 的非遞減順序來避免排列重複;剩餘總和不足就剪枝。
class Solution:
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
candidates.sort()
result = []
path = []
def search(start: int, remaining: int) -> None:
if remaining == 0:
result.append(path.copy())
return
for index in range(start, len(candidates)):
value = candidates[index]
if value > remaining:
break
path.append(value)
search(index, remaining - value)
path.pop() # Undo this choice before exploring another.
search(0, target)
return result
c 為候選數,D=⌊target/min(candidates)⌋,R 為結果數;包含輸出,排除輸出為 O(D)。
[2,3], target=6
choose 2 → 2 → 2: remaining 0 → save [2,2,2]
undo choices; choose 3 → 3 → save [3,3]
No [3,2,...] branch: indices never move backward.中文:把「選擇、探索、撤銷」說清楚,也要解釋如何避免重複組合。
加權抽樣、資料池與分組是訓練管線的周邊能力。模型架構、loss、gradient、optimizer、fine-tuning 與蒸餾,應以 NumPy / PyTorch 實作為主要補強。
工作主題Training / Adaptation · RL / Decisions
解題技術Prefix Sum · Binary Search · Randomized
訓練資料加權抽樣的基礎;固定權重抽樣本身不會學習 bandit policy。
每次回傳一個 index,使機率等於該位置權重除以總權重。
w=[1,3] → index 0 機率 1/4,index 1 機率 3/4(單次結果不固定)
把權重變成累積區間;均勻抽取票號,再二分找到所屬區間。
n 為權重數;這是有放回抽樣。
工作主題Training / Adaptation · RL / Decisions · Production / Efficiency
解題技術Hash Map · Design · Randomized
可類比需要增刪與均勻抽樣的資料池;它是 set,不保留重複 transition。
設計集合,支援插入、刪除與等機率隨機取值,平均每個操作 O(1)。
insert(8) → true; insert(5) → true; remove(8) → true; getRandom() → 5
陣列提供隨機索引,map 記錄位置;刪除時以最後一個元素補洞並更新索引。
from random import choice
class RandomizedSet:
def __init__(self):
self.values = []
self.positions = {}
def insert(self, val: int) -> bool:
if val in self.positions:
return False
self.positions[val] = len(self.values)
self.values.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.positions:
return False
index = self.positions[val]
last = self.values[-1]
self.values[index] = last
self.positions[last] = index
self.values.pop()
del self.positions[val]
return True
def getRandom(self) -> int:
return choice(self.values)
n 為目前集合大小;getRandom 僅在非空集合呼叫。
values=[8,5,9], positions={8:0,5:1,9:2}
remove(5): put 9 in slot 1, update positions[9], pop last
values=[8,9], positions={8:0,9:1}中文:用最後一個元素補洞,避免陣列刪除造成整段搬移。
House Robber 與 Minimum Path Sum 練的是已知規則下的最佳子結構。RL 還要從互動資料學習,處理未知結果、探索/利用、reward 與 credit assignment。
工作主題RL / Decisions
解題技術Dynamic Programming
練習 state、action、累積 reward 的定義;這是已知資料的 DP,不是 RL 訓練。
從非負數列中選取互不相鄰的元素,求最大總和。
nums=[2,7,9,3,1] → 12(2+9+1)
每一步比較跳過目前值,或取目前值加上前兩格最佳值。
n 為元素數。
工作主題RL / Decisions · Agents / Planning
解題技術Dynamic Programming
練習已知 transition 與 cost 的最佳決策;延伸才是 MDP / value iteration。
從非負 grid 左上到右下,每次向右或向下,回傳沿途最小總和。
grid=[[1,3],[2,1]] → 4
目前格子的最小成本 = 自身成本 + min(上方最佳, 左方最佳)。
r、c 為列、欄數;選擇不修改輸入的一維 DP 版本。
Prefix Sum、Median 與 Sliding Window Maximum 是統計資料處理基礎;A/B testing、confidence intervals、因果識別與 ablation 的設計不能用它們替代。
工作主題Evaluation / Causal · Production / Efficiency
解題技術Prefix Sum
固定資料的區間聚合基礎;不涉及顯著性或因果效果。
初始化不可變陣列後,多次查詢閉區間 [left,right] 的元素總和。
nums=[2,4,6]; sumRange(1,2) → 10
prefix[i] 代表前 i 項總和,用 prefix[right+1] - prefix[left] 回答查詢。
n 為元素數。
工作主題Evaluation / Causal · Production / Efficiency
解題技術Heap · Design
線上統計摘要;本題維持精確 median,需要保留所有值。
支援新增數值與查詢目前全部數值的中位數。
addNum(2), addNum(8) → median 5;再 addNum(3) → median 3
兩個 heap 分別保留較小半與較大半,維持順序與大小平衡。
n 為已加入數量;與近似 quantile sketch 不同。
工作主題Evaluation / Causal · Production / Efficiency
解題技術Sliding Window · Monotonic Queue
時間窗極值、監控尖峰的基礎;最大值不是 p95/p99。
固定長度 k 的窗口依序向右滑動,回傳每個窗口的最大值。
nums=[1,3,-1,2], k=2 → [3,3,2]
Deque 存 index 並保持對應值遞減;更晚且更大的元素會淘汰較早的小值。
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
candidates = deque()
answer = []
for right, value in enumerate(nums):
while candidates and candidates[0] <= right - k:
candidates.popleft()
while candidates and nums[candidates[-1]] <= value:
candidates.pop()
candidates.append(right)
if right >= k - 1:
answer.append(nums[candidates[0]])
return answer
n 為陣列長度;每個 index 最多進出 deque 一次。
nums=[1,3,-1,2], k=2
r=0: deque values [1]
r=1: 3 removes 1 → [3] → output 3
r=2: [3,-1] → output 3
r=3: expire 3; 2 removes -1 → [2] → output 2中文:淘汰較舊又較小的元素是正確性核心,index 則負責判斷過期。
快取、版本查詢、排程與串流聚合是很實用的 coding 題型。延伸到 ML serving 時,還要測 batch shape、記憶體與 latency,並區分 cache policy 和模型張量快取。
工作主題Production / Efficiency · Agents / Planning
解題技術Hash Map · Linked List · Design
有容量上限的查詢結果快取;LRU 淘汰政策和 transformer KV cache 是不同概念。
支援 get / put;容量滿時淘汰最久未使用項目,各操作平均 O(1)。
capacity=2; put(1,10), put(2,20), get(1), put(3,30) → key 2 被淘汰
Hash map 找 node,doubly linked list 維持新舊次序;讀寫後都移到最新端。
需維護 map 與串列一致性;更新舊 key 不應增加項目數。
工作主題Production / Efficiency · Evaluation / Causal · Agents / Planning
解題技術Hash Map · Binary Search · Design
版本查詢與 point-in-time lookup 基礎;資料可用時間仍需另行建模。
保存 key 的多個時間版本,查詢不晚於給定時間的最新值,沒有則回傳空字串。
set("x","old",2), set("x","new",5); get("x",4) → "old"
每個 key 的版本按時間 append;二分找最後一個 timestamp ≤ query 的版本。
v 為該 key 的版本數,N 為總寫入數;前提是寫入時間遞增。
工作主題Production / Efficiency · Agents / Planning
解題技術Greedy · Hash Map
冷卻限制下的排程;是 rate-limit / throughput 思考的簡化模型。
同字母任務之間需至少隔 n 個時間單位,任務各花一單位,求含 idle 的最短完成時間。
tasks=["A","A","B"], n=2 → 4(A,B,idle,A)
最高頻率 f 決定 (f-1)(n+1)+t 的框架,t 是同最高頻種類數;與任務總數取 max。
T 為任務數;題目字母種類固定 26。
影像部分先練座標、矩陣與連通區塊;speech 可以用 Edit Distance 延伸到 WER / CER。跨模態對齊、特徵抽取與生成模型需要另行練習。
解題技術Graph
像素連通區域操作;是 image processing 基礎,不是訓練 segmentation model。
由起點把四方向連通、與起點原色相同的區域全部改色。
image=[[1,1],[1,0]], sr=0, sc=0, color=2 → [[2,2],[2,0]]
BFS 入隊時改色當作 visited;原色等於新色時直接結束。
r、c 為影像尺寸;BFS queue 最壞可佔相同量級。
解題技術Graph
二值 mask 的 connected-component 計數基礎。
在字元 '1' / '0' 的網格中,計算四方向相連的陸地群數。
grid=[["1","0"],["0","1"]] → 2
掃到未訪問陸地就建立一座島,再用 BFS 標記整個連通塊。
from collections import deque
class Solution:
def numIslands(self, grid: list[list[str]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
seen = set()
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != "1" or (r, c) in seen:
continue
count += 1
seen.add((r, c))
queue = deque([(r, c)])
while queue:
x, y = queue.popleft()
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if (0 <= nx < rows and 0 <= ny < cols
and grid[nx][ny] == "1"
and (nx, ny) not in seen):
seen.add((nx, ny))
queue.append((nx, ny))
return count
r、c 為網格尺寸;這份解法以 seen 保存訪問記錄,保留輸入。
grid=[["1","0"],["0","1"]]
Start at (0,0): island 1, no adjacent land
Start at (1,1): island 2 → return 2中文:每次從未走過的陸地啟動 BFS,就找到一個新的連通區塊。
解題技術Matrix
影像幾何操作的基礎;檢查座標映射與 in-place 約束。
將 n×n 矩陣原地順時針旋轉 90 度。
matrix=[[1,2],[3,4]] → [[3,1],[4,2]]
先轉置,再反轉每列;對應 (r,c) → (c,n-1-r)。
class Solution:
def rotate(self, matrix: list[list[int]]) -> None:
n = len(matrix)
for r in range(n):
for c in range(r + 1, n):
matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
for row in matrix:
row.reverse()
n 為正方形邊長;使用交換,不建立新矩陣。
[[1,2],[3,4]]
transpose → [[1,3],[2,4]]
reverse rows → [[3,1],[4,2]]中文:先用座標映射說明正確性,再拆成轉置與反轉每列。
括號與 regex 題只練結構/格式驗證。它們無法評估 hallucination、fairness、adversarial robustness 或 interpretability;這類職缺應提高下方直接實作的優先度。
工作主題Safety / Interpretability · NLP / LLM
解題技術Stack
只練結構合法性檢查;括號正確不能證明輸出安全或事實正確。
判斷只含 ()[]{} 的字串,括號類型與巢狀配對順序是否正確。
"([])" → true;"([)]" → false
Stack 記錄尚未關閉的左括號;每個右括號必須匹配最後開啟的括號。
class Solution:
def isValid(self, s: str) -> bool:
matching = {")": "(", "]": "[", "}": "{"}
stack = []
for char in s:
if char in matching:
if not stack or stack.pop() != matching[char]:
return False
else:
stack.append(char)
return not stack
n 為字串長度。
"([])": push (, push [, match ], match ) → true
"([)]": ) does not match the top [ → false中文:配對需要最後開、最先關,因此使用 stack,而不是只計數。
工作主題Safety / Interpretability · NLP / LLM
解題技術Dynamic Programming · String Parsing
有限格式規則的匹配;regex 不是 prompt-injection 或幻覺防線。
判斷字串是否整段符合 pattern:'.' 代表任一字元,'*' 使前一元素重複零次以上。
s="aab", p="c*a*b" → true
Memoized DP(i,j):遇 x* 可跳過該組,或匹配一個字元後繼續留在同組。
m、n 為字串與 pattern 長度;需記憶化避免重複子問題。
若是一般 coding round,先做起步題並計時;若明確要求 NumPy / PyTorch / ML coding,從相應主題的直接實作開始。Applied / Research Scientist 的實際面試內容以該團隊提供的資訊為準。
題目描述與延伸練習皆為原創摘要/整理。8 題新解法放在可展開區塊中;20 題重複內容連回既有 HTML。新解法採 Python 3;LeetCode 271 的題面需要 Premium,可先閱讀 NeetCode 對應頁。