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

LeetCode 3195: Find the Minimum Area to Cover All Ones I

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

基本資料
#

難易度: medium 第一次嘗試:2025-08-22

  • 提交紀錄:Accepted(一次通過)

解題思路
#

矩形的邊要平行格線,要包住所有的 1,最小的就是剛好貼著最外圍的 1(Array 模板五):上邊是最上面那個 1 的列,下邊是最下面的列,左右同理。面積是 (max_r - min_r + 1) × (max_c - min_c + 1)。

我的解法
#

class Solution:
    def minimumArea(self, grid: List[List[int]]) -> int:
        rows = [i for i, row in enumerate(grid) if 1 in row]
        cols = [j for j in range(len(grid[0])) if any(row[j] for row in grid)]
        return (rows[-1] - rows[0] + 1) * (cols[-1] - cols[0] + 1)

我當時用兩層迴圈逐格更新四個邊界,跑了將近 3 秒;這裡改成先找有 1 的列、再找有 1 的欄,1 in row 是內建的掃描,比較快。

複雜度
#

時間 O(m · n),空間 O(m + n)。

要特別避免的錯誤
#

  • 邊界是包含的,高和寬都要加 1。

面試口說整理
#

最小的矩形剛好貼著最外圍的 1,所以我找出有 1 的最上、最下列和最左、最右欄,相減加 1 再相乘。時間 O(mn)。

相關文章

LeetCode 1222: Queens That Can Attack the King
·1 分鐘
LeetCode Medium Array Matrix Simulation
LeetCode 1222 解題筆記:從國王往八個方向一步一步走,每個方向第一個遇到的皇后就能攻擊;皇后放進集合方便查詢
LeetCode 3070: Count Submatrices with Top-Left Element and Sum Less Than k
·1 分鐘
LeetCode Medium Array Matrix Prefix-Sum
LeetCode 3070 解題筆記:包含左上角的子矩陣就是二維前綴和 P[i][j],數有幾個 <= k
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 解題筆記:反過來從海邊往內走,只能走到不比自己低的格子;兩個海都走得到的格子就是答案