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

LeetCode 74: Search a 2D Matrix

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

基本資料
#

難易度: medium 第一次嘗試:2022-10-25

  • 提交紀錄:Runtime Error ×3 → Wrong Answer → Runtime Error → Wrong Answer ×2 → Accepted ×3 → Runtime Error ×4 → Wrong Answer → Runtime Error ×3 → Wrong Answer → Accepted → Runtime Error → Wrong Answer → Accepted → Wrong Answer → Accepted ×2 → Runtime Error → Time Limit Exceeded → Runtime Error → Accepted → Runtime Error → Accepted ×3

解題思路
#

每一列由小到大,而且每列的開頭比上一列的結尾大,所以整個矩陣攤平就是一個排序好的陣列(Binary Search 模板一)。在 [0, m·n - 1] 上二分,index mid 對應到 matrix[mid // n][mid % n]。

我的嘗試
#

這題 2022 年提交了 34 次,是這批裡最多的:

  • 一開始先找列再找欄,條件用了嚴格的 >,目標剛好是某一列的第一個時找不到。例如 [[1], [15]]、target = 1 回傳 False。
  • 改成攤平二分之後,好幾版 mid = (low + high) / 2 得到浮點數(TypeError);也有幾版變數沒定義、index 超出範圍。

正確解法
#

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])
        l, r = 0, m * n - 1
        while l <= r:
            mid = (l + r) // 2
            v = matrix[mid // n][mid % n]
            if v == target:
                return True
            if v < target:
                l = mid + 1
            else:
                r = mid - 1
        return False

複雜度
#

時間 O(log(m · n)),空間 O(1)。

要特別避免的錯誤
#

  • 換算座標除以的是欄數 n。
  • mid 要用整數除法。

面試口說整理
#

矩陣攤平後是排序好的,所以我直接在 0 到 m·n - 1 之間二分,把 mid 換成列 mid // n、欄 mid % n。時間 O(log(mn))。

相關文章

LeetCode 73: Set Matrix Zeroes
·1 分鐘
LeetCode Medium Array Hash-Table Matrix
LeetCode 73 解題筆記:先記下哪些列、哪些欄有 0,掃完之後再一起改;進階用第一列、第一欄當標記
LeetCode 54: Spiral Matrix
·1 分鐘
LeetCode Medium Array Matrix Simulation
LeetCode 54 解題筆記:維護上下左右四個邊界,依序走右、下、左、上,每走完一邊就把那個邊界往內縮
LeetCode 59: Spiral Matrix II
·1 分鐘
LeetCode Medium Array Matrix Simulation
LeetCode 59 解題筆記:跟 LC 54 一樣維護四個邊界,只是把讀取換成依序填入 1 到 n²
LeetCode 33: Search in Rotated Sorted Array
·1 分鐘
LeetCode Medium Array Binary-Search
LeetCode 33 解題筆記:旋轉後 mid 的左右一定有一邊是排序好的,判斷目標在不在那一邊,在就往那邊找,不在就去另一邊
LeetCode 34: Find First and Last Position of Element in Sorted Array
·1 分鐘
LeetCode Medium Array Binary-Search
LeetCode 34 解題筆記:做兩次 lower bound:第一個 >= target 的位置,以及第一個 >= target + 1 的位置減一
LeetCode 36: Valid Sudoku
·1 分鐘
LeetCode Medium Array Hash-Table Matrix
LeetCode 36 解題筆記:每個數字在列、欄、3 × 3 宮格各只能出現一次;用 (數字, 列)、(數字, 欄)、(數字, 宮格) 當 key 放進同一個集合