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

LeetCode 3070: Count Submatrices with Top-Left Element and Sum Less Than k

·1 分鐘· ·
LeetCode Medium Array Matrix Prefix-Sum
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2024-03-03

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

解題思路
#

包含 (0, 0) 的子矩陣由右下角 (i, j) 決定,總和就是二維前綴和 P[i][j] = grid[i][j] + P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1](Prefix Sum)。要減掉重複加的左上角 P[i - 1][j - 1]。數有幾個 P[i][j] <= k。

我的嘗試
#

2024 年比賽時錯了兩次:

  • 第一版原地累加上面和左邊,沒有減掉左上角,重疊的部分算了兩次:[[1, 0], [4, 4]]、k = 9 右下角算成 10,回傳 3,答案 4。
  • 改成先算每一列的前綴和、再加上上一列的結果(等於沒有重複),但條件寫成 < k:[[3]]、k = 3 回傳 0。改成 <= 就 AC 了。

正確解法
#

class Solution:
    def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
        m, n = len(grid), len(grid[0])
        P = [[0] * (n + 1) for _ in range(m + 1)]
        count = 0
        for i in range(m):
            for j in range(n):
                P[i + 1][j + 1] = grid[i][j] + P[i][j + 1] + P[i + 1][j] - P[i][j]
                count += P[i + 1][j + 1] <= k
        return count

複雜度
#

時間 O(mn),空間 O(mn)。

要特別避免的錯誤
#

  • 二維前綴和要減掉左上角,不然重疊的部分算了兩次。
  • 條件是 <= k。

面試口說整理
#

包含左上角的子矩陣就是以每一格為右下角的二維前綴和,我用上面加左邊減左上角的公式算出來,數有幾個不超過 k。時間 O(mn)。

相關文章

LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid
·1 分鐘
LeetCode Medium Array Hash-Table Matrix Counting
LeetCode 3071 解題筆記:分別數 Y 上和 Y 外每個值的次數,枚舉 Y 的值 a 和背景的值 b(a != b),取最少要改的格子數
LeetCode 240: Search a 2D Matrix II
·1 分鐘
LeetCode Medium Array Binary-Search Divide-and-Conquer Matrix
LeetCode 240 解題筆記:從右上角開始,比目標大就往左、比目標小就往下,每一步排除一整列或一整欄
LeetCode 48: Rotate Image
·1 分鐘
LeetCode Medium Array Math Matrix
LeetCode 48 解題筆記:順時針轉 90 度 = 先轉置再把每一列左右反轉,兩步都可以原地做
LeetCode 417: Pacific Atlantic Water Flow
·1 分鐘
LeetCode Medium Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 417 解題筆記:反過來從海邊往內走,只能走到不比自己低的格子;兩個海都走得到的格子就是答案
LeetCode 238: Product of Array Except Self
·1 分鐘
LeetCode Medium Array Prefix-Sum
LeetCode 238 解題筆記:答案是左邊所有數的乘積乘上右邊所有數的乘積,兩次掃描,不用除法
LeetCode 73: Set Matrix Zeroes
·1 分鐘
LeetCode Medium Array Hash-Table Matrix
LeetCode 73 解題筆記:先記下哪些列、哪些欄有 0,掃完之後再一起改;進階用第一列、第一欄當標記