Top 150 Interview簡単

Search a 2D Matrix

Detailed guide and Python implementation for the 'Search a 2D Matrix' problem.

問題提起

簡単

You are given an m x n integer matrix matrix with the following two properties:

- Each row is sorted in non-decreasing order.

- The first integer of each row is greater than the last integer of the previous row.

Given an integer target, return True if target is in matrix or False otherwise.

You must write a solution in O(log(m * n)) time complexity.

Write a function 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?
Consider using Binary Search-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

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 リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。