組力扣復(fù)習(xí))
56. 合并區(qū)間 - 力扣LeetCodeclass Solution: def merge(self, intervals: list[list[int]]) - list[list[int]]: intervals.sort(keylambda it: it[0]) res[] for start,end in intervals: if res and startres[-1][1]: res[-1][1]max(res[-1][1],end) else: res.append([start,end]) return res思路按左端點排序重疊就擴右端否則開新區(qū)間易錯點① 右端更新必須取max[1,10]后跟[2,3]直接賦值會將 10 錯改成 3② 重疊判斷用[1,2]和[2,3]相接也需合并③ 時間復(fù)雜度由 .sort() 方法主導(dǎo)為 O(nlogn)④ .sort() 是一個原地操作會直接改變對象內(nèi)部的排序情況改變后對應(yīng)次序不會被消除189. 輪轉(zhuǎn)數(shù)組 - 力扣LeetCodeclass Solution: def rotate(self, nums: list[int], k: int) - None: Do not return anything, modify nums in-place instead. nlen(nums) k%n def reverse(i,j): while ij: nums[i],nums[j]nums[j],nums[i] i1 j-1 reverse(0,n-1) reverse(0,k-1) reverse(k,n-1)口訣整體反轉(zhuǎn)負責(zé)換位局部反轉(zhuǎn)負責(zé)復(fù)原易錯點①k % n取模不能漏k n 時應(yīng)原樣不動k n 時不取模會越界② 原地修改、無返回值時間復(fù)雜度 O(n)空間復(fù)雜度 O(1)238. 除了自身以外數(shù)組的乘積 - 力扣LeetCodeclass Solution: def productExceptSelf(self, nums: List[int]) - List[int]: nlen(nums) res[1]*n for i in range(1,n): res[i]res[i-1]*nums[i-1] suffix1 for i in range(n-1,-1,-1): res[i]*suffix suffix*nums[i] return res易錯點① 第二遍res[i] * suffix與suffix * nums[i]的順序不能反suffix 必須是 嚴格右側(cè) 的積先更新就將自己乘入了邏輯錯誤② 第一遍下標(biāo)從 1 開始、乘nums[i-1]因為res[0]左側(cè)沒有元素追問如果允許除法怎么處理 0 元素0 多于一個全 0恰好一個 0只有 0 那個位置是 其余數(shù)之積其他位置全 0沒有 0總積除以自己