> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/240.search_a_2d_matrix_ii.md).

# 240.Search a 2D Matrix II

**240.Search a 2D Matrix II**

难度：Medium

> 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性： 每行的元素从左到右升序排列。 每列的元素从上到下升序排列。 示例:

```
现有矩阵 matrix 如下：

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
```

给定 target = 5，返回 true。 给定 target = 20，返回 false。

解决方法：因为都是有序排列，最开始想使用二分法，但是以超时告终。\
所以还是要找规律，从数组的右上角看，如果该数字比target大，则该列所有数都比target大，该列可以忽略寻找；如果该数字比target小，则该行所有数都比target小，该行也可以放弃寻找。\
从左下角开始判断也是一样的效果。\
代码如下：

```
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.empty() || matrix[0].empty()) return false;
        int row=matrix.size();
        int col=matrix[0].size();
        if(matrix[row-1][col-1]<target) return false;
        int rstart=0,cstart=col-1;
        while( rstart<row && cstart >= 0)
        {
            if(matrix[rstart][cstart] == target) return true;
            else if(matrix[rstart][cstart] < target) ++rstart;
            else  --cstart;
            
        }           
        return false;
        
        
    }
};
```

在搜索判断中，如果碰到相等的就跳出循环返回`true`，搜索到左下角后，还没找到，返回`false`。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/240.search_a_2d_matrix_ii.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
