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

LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid

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

基本資料
#

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

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

解題思路
#

Y 由三段組成:左上到中心、右上到中心、中心到最下面(Matrix 模板三)。先數 Y 上和 Y 外 0、1、2 各有幾個(Hash Table),再枚舉 9 種 (a, b) 中 a != b 的 6 種,要改的格子數是 Y 的總數 - Y 上值為 a 的個數 + 背景總數 - 背景值為 b 的個數。

我的嘗試
#

一次 AC。

正確解法
#

class Solution:
    def minimumOperationsToWriteY(self, grid: List[List[int]]) -> int:
        n = len(grid)
        mid = n // 2
        on, off = [0] * 3, [0] * 3
        for i in range(n):
            for j in range(n):
                in_y = (i <= mid and (j == i or j == n - 1 - i)) or (i >= mid and j == mid)
                (on if in_y else off)[grid[i][j]] += 1
        total_on, total_off = sum(on), sum(off)
        return min(total_on - on[a] + total_off - off[b]
                   for a in range(3) for b in range(3) if a != b)

複雜度
#

時間 O(n²),空間 O(1)。

要特別避免的錯誤
#

  • 中心點屬於三段,只能算一次。
  • Y 和背景的值必須不同。

面試口說整理
#

我先分別數 Y 上和 Y 外每個值的次數,再枚舉 Y 的值和背景的值兩兩不同的六種組合,要改的就是兩邊不等於目標值的格子數,取最小。時間 O(n²)。

相關文章

LeetCode 229: Majority Element II
·1 分鐘
LeetCode Medium Array Hash-Table Sorting Counting
LeetCode 229 解題筆記:超過 n / 3 的數最多兩個;Boyer-Moore 維護兩個候選人,最後再掃一次確認次數
LeetCode 73: Set Matrix Zeroes
·1 分鐘
LeetCode Medium Array Hash-Table Matrix
LeetCode 73 解題筆記:先記下哪些列、哪些欄有 0,掃完之後再一起改;進階用第一列、第一欄當標記
LeetCode 36: Valid Sudoku
·1 分鐘
LeetCode Medium Array Hash-Table Matrix
LeetCode 36 解題筆記:每個數字在列、欄、3 × 3 宮格各只能出現一次;用 (數字, 列)、(數字, 欄)、(數字, 宮格) 當 key 放進同一個集合
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 240: Search a 2D Matrix II
·1 分鐘
LeetCode Medium Array Binary-Search Divide-and-Conquer Matrix
LeetCode 240 解題筆記:從右上角開始,比目標大就往左、比目標小就往下,每一步排除一整列或一整欄
LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
·1 分鐘
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 106 解題筆記:後序的最後一個是根;從後序尾巴往前取根時,要先建右子樹再建左子樹