起床時間:0600
今天問了GPT比較好的刷題方法,決定跟著他的方法試試看。所以今天隨機抽一題!
不過今天只完成到Step4,還沒空寫Step5關聯題
主要是因為Python語法實在太不熟了...
其實就算看完PseuCode再次重寫也好容易錯
大家都怎麼刷題的,還在前期灰心狀態欸,沒進去Zone
短時限嘗試(10–15 分鐘)
只做三件事:
分級揭示
卡住就依序只看:題目 tags → 一句提示 → 「核心思路圖/解法段落」。
不要一次把完整程式碼看完。
帶任務讀解法(5–10 分鐘)
只讀兩個來源:官方/NeetCode 思路+一個高票解。閱讀時回答三題:
關書重寫(10–15 分鐘)
關掉解答,從空白檔把核心解法寫出來,再手跑你的小樣例。最後標註:時間/空間複雜度、易錯點。
變體一題(5 分鐘)
同題型換一個小變體:例如 Two Sum →「有序陣列版」或「回傳是否存在而非索引」。強化「模式」而非「題號」。
間隔重複
同一題在 隔天 和 第 3–7 天 各「閉卷重寫」一次(限時 10 分鐘)。能在 10 分鐘內從零寫完且全 AC,才算畢業。
Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
You may return the answer in any order.
Note: Intervals are non-overlapping if they have no common point. For example, [1, 2] and [3, 4] are non-overlapping, but [1, 2] and [2, 3] are overlapping.
其實一開始看不懂題目,看半天看不懂Example。
這樣理解就懂了
題目給你一堆時間段(區間),格式是 [start, end]。
你要把有重疊的時間段合併,得到一份「最簡」的時間表。
自己隨便在紙上想了幾個小樣後,可以寫出不正確的暴力解。但是至少是個開始QQ
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
id1
id2
line = [id1, id2]
sol = List[subList[int]]
for line in intervals:
for sublist in sol:
if solid1 < id1 < solid2 && id2 > solid2:
remove(sublist)
sol.add([solid1, id2])
題目類型判斷有猜到2point。
Step2 核心思路 就是要先 Sort
因為Python語法不熟,目前有三個要讀
1.暴力解的正確思路 & 寫法
2.正解的思路(pseudocode code)
3.正確的寫法
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: sort(intervals, key=s) curs, cure = intervals[0] res=[] for s, e in intervals[1:]: if curs >= s: res.append[curs, max(cure, e)] else: res.append[s, e] curs = s, cure = e return res[]
排序用法錯:sort(intervals, key=s)
應是就地排序:intervals.sort(key=lambda x: x[0])(按 start)。
重疊判斷顛倒:
正確判斷是「下一段的 s 是否 ≤ 目前 cur 的 end」:if s <= cure:
你寫成 if curs >= s:,方向與意義都不對。
合併時機錯:
「重疊」時不要立刻 append,只需擴張 cur:cure = max(cure, e)。
「不重疊」時才把 cur 推進 res,並重設 cur = [s, e]。
你現在兩個分支都在 append,導致會重複/切碎。
cur 更新時機錯:
你寫 curs = s, cure = e(且語法也錯)。
正確是:只有不重疊時才把 cur 換成新區間;重疊時只更新 cure。
語法小錯:
res.append[...] 應該是 res.append([...])。
return res[] 應該是 return res。
curs = s, cure = e 應該是 curs, cure = s, e(且如上所述,不是每次都要換)。
漏了最後一次 push:
迴圈結束後,別忘把最後的 cur 放進 res。
Invariant 未被維持:
正確 invariant:res 內的區間皆不重疊且在 cur 之前;cur=[curs,cure] 為目前能擴張到的最大合併區間。
你現在在重疊時就 append,破壞了這個 invariant。