# 74 Search a 2D Matrix

## 74. [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/description/)

## 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`, return`true`.

## 2. Implementation

**(1) Binary Search**

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

```java
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) {
            return false;
        }

        int m = matrix.length, n = matrix[0].length;
        int start = 0, end = m * n - 1, mid = 0;

        while (start <= end) {
            mid = start + (end - start) / 2;
            int row = mid / n;
            int col = mid % n;

            if (matrix[row][col] == target) {
                return true;
            }
            else if (matrix[row][col] < target) {
                start = mid + 1;
            }
            else {
                end = mid - 1;
            }
        }
        return false;
    }
}
```

## 3. Time & Space Complexity

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/binary-search/74-search-a-2d-matrix.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
