150強訪談簡單

搜尋二維矩陣

“搜尋二維矩陣”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個 m x n 整數矩陣 matrix ,具有下列兩個屬性:

- 每行以非降序排序。

- 每行的第一個整數大於前一行的最後一個整數。

給定一個整數 target,如果 target 位於 matrix 中,則傳回 True ,否則傳回 False

您必須以 O(log(m * n)) 時間複雜度編寫解決方案。

寫一個函數 searchMatrix(matrix: List[List[int]], target: int) -> bool

約束條件
  • m == len(matrix)
  • n == len(matrix[i])
  • 1 <= m, n <= 100
  • -10^4 <= matrix[i][j], target <= 10^4

範例

Example 1
Input
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 3
Output
True
Explanation

3 is found in the first row at index 1.

Example 2
Input
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 13
Output
False
Explanation

13 is not present in the matrix.

Need a Hint?
考慮使用二分搜尋特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。