# 74. Search a 2D Matrix

Write an efficient algorithm that searches for a value in an _m_ x _n_ matrix. 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.

**Example 1:**

```
Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true
```

**Example 2:**

```
Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false
```

```cpp
bool searchMatrix(vector<vector<int>>& matrix, int target) { // time: O(m + n); space: O(1)
    if (matrix.empty() || matrix[0].empty() || 
        matrix[0][0] > target || matrix.back().back() < target) return false;
    int m = matrix.size(), n = matrix[0].size();
    int row = 0, col = n - 1;
    while (row < m && col >= 0) {
        if (matrix[row][col] > target) --col;
        else if (matrix[row][col] < target) ++row;
        else return true;
    }
    return false;
}
```

```cpp
bool searchMatrix(vector<vector<int>>& matrix, int target) { // time: O(log(mn)); space: O(1)
    if (matrix.empty() || matrix[0].empty() || 
        matrix[0][0] > target || matrix.back().back() < target) return false;
    int m = matrix.size(), n = matrix[0].size(), low = 0, high = m * n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2, row = mid / n, col = mid % n;
        if (matrix[row][col] > target) high = mid - 1;
        else if (matrix[row][col] < target) low = mid + 1;
        else return true;
    }
    return false;
}
```

```cpp
bool searchMatrix(vector<vector<int>>& matrix, int target) { // time: O(logm + logn); space: O(1)
    if (matrix.empty() || matrix[0].empty() || 
        matrix[0][0] > target || matrix.back().back() < target) return false;
    int m = matrix.size(), n = matrix[0].size();
    int low = 0, high = m - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (matrix[mid][0] > target) high = mid - 1;
        else if (matrix[mid][0] < target) low = mid + 1;
        else return true;
    }
    int tmp = high;
    low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (matrix[tmp][mid] > target) high = mid - 1;
        else if (matrix[tmp][mid] < target) low = mid + 1;
        else return true;
    }
    return false;
}
```

{% content-ref url="240.-search-a-2d-matrix-ii" %}
[240.-search-a-2d-matrix-ii](240.-search-a-2d-matrix-ii)
{% endcontent-ref %}
