↓快轉到主要內容
  1. LeetCode/

LeetCode 598: Range Addition II

·1 分鐘· ·
LeetCode Easy Array Math
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-28

  • 提交紀錄:Wrong Answer → Accepted ×3 → Runtime Error ×2 → Accepted ×2

解題思路
#

每次操作都是從 (0, 0) 開始的矩形,所以被所有操作都加到的格子就是最大值,也就是所有矩形的交集:列數取 min(a)、行數取 min(b),兩者分開取最小值再相乘(Math 模板四)。沒有操作時整個矩陣都是 0,答案是 m × n。

我的嘗試
#

第一版在列和行的最小值不同時回傳 min(min_row, min_column) ** 2,把交集當成正方形:m = 4、n = 1、ops = [[2, 1]] 答案 2,回傳 1。之後兩版 RE(變數名稱錯誤、型別錯誤),改成兩者相乘就 AC 了。

正確解法
#

class Solution:
    def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
        for a, b in ops:
            m, n = min(m, a), min(n, b)
        return m * n

複雜度
#

時間 O(k)(k 是操作數),空間 O(1)。

要特別避免的錯誤
#

  • 交集不一定是正方形,列和行各自取最小值。
  • 沒有操作時答案是 m × n。

面試口說整理
#

每次操作都包含左上角,所以被加最多次的格子是所有操作的交集,我分別取列數和行數的最小值相乘;沒有操作時把 m、n 當成初始值就自然是 m × n。時間 O(k)。

相關文章

LeetCode 268: Missing Number
·1 分鐘
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 解題筆記:0 到 n 的總和減掉陣列總和就是缺的那個;缺的可能是 0
LeetCode 66: Plus One
·1 分鐘
LeetCode Easy Array Math
LeetCode 66 解題筆記:從最後一位往前加一,遇到 9 變 0 繼續進位,全部都是 9 時前面補 1
LeetCode 599: Minimum Index Sum of Two Lists
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 599 解題筆記:把 list1 的字串對應到 index,掃 list2 時算兩邊 index 的和,留下和最小的全部字串
LeetCode 605: Can Place Flowers
·1 分鐘
LeetCode Easy Array Greedy
LeetCode 605 解題筆記:從左到右,左右都空的空格就種下去;種下去的花會擋住下一格,要真的更新陣列
LeetCode 561: Array Partition
·1 分鐘
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 解題筆記:排序後相鄰兩個一組,每組的最小值就是偶數位置的數,加總
LeetCode 566: Reshape the Matrix
·1 分鐘
LeetCode Easy Array Matrix Simulation
LeetCode 566 解題筆記:元素總數不同就回傳原矩陣;否則第 k 個元素放到 (k // c, k % c)