# 240. Search a 2D Matrix II

{% hint style="success" %}
find the fisrt position in a row bigger than target, then throw corresponded columns

consider edge case
{% endhint %}

![](https://3288217904-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LxJcc9A1TOyn5a5HJQ4%2F-M6vGzbxvPi_aaIx0CUY%2F-M6vMxtfDZTPtHWtqbxf%2FWechatIMG630.png?alt=media\&token=814d86ba-257e-4d7e-ada1-37321ec48c68)

> matrix is `m` rows and `n` columns, `m * n`

### Solution 1:

check from first to last row, find the first position in a row bigger than target, then throw one row or a few columns with one row

do search insertion position in each row

time complexity: $$O(m\*lg(n))$$&#x20;

### Soultion 2:

check from right top or left bottom element, every time throw one column or row

Time complexity: $$O(m+n)$$&#x20;

{% tabs %}
{% tab title="Java" %}

```java
// Some code
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length - 1, col = 0;
        while(row >= 0 & col <= matrix[0].length - 1) {
            if(matrix[row][col] == target)
                return true;
            else if(matrix[row][col] > target)
                row --;
            else
                col ++;
        }
        
        return false;
    }
}
```

{% endtab %}
{% endtabs %}


---

# 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://r24zeng.gitbook.io/leetcode-notebook/wan-quan-an-zhao-jiu-zhang-suan-fa-shua-de-60-dao-zuo-you/binary-search/240.-search-a-2d-matrix-ii.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.
