74 Search a 2D Matrix

1. Question

Write an efficient algorithm that searches for a value in anmxnmatrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.

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

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target=3, returntrue.

2. Implementation

(1) Binary Search

思路: 因为每一行的第一个数肯定比上一行的最后一个数大,所以matrix[0][0]到matrix[m - 1][n - 1]是严格递增的, 可以直接把matrix降成一维数组,对这个一维数组进行二分查找

3. Time & Space Complexity

时间复杂度O(logmn), m为matrix的行数, row为matrix的列数,空间复杂度O(1)

Last updated

Was this helpful?