> For the complete documentation index, see [llms.txt](https://imhuay.gitbook.io/studies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/niu-ke-0086-zhong-deng-ju-zhen-yuan-su-cha-zhao.md).

# 矩阵元素查找

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E4%B8%AD%E7%AD%89\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#中等) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/04/pages/R5NyOzkn3qAZy7wCx1pS#二分查找)

> [矩阵元素查找\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/3afe6fabdb2c46ed98f06cfd9a20f2ce)

**问题简述**

```
已知一个有序矩阵mat，同时给定矩阵的大小n和m以及需要查找的元素x，且矩阵的行和列都是从小到大有序的。设计查找算法返回所查找元素的二元数组，代表该元素的行号和列号(均从零开始)。保证元素互异。
```

**思路**

* 从左上角开始查找，大于 `x` 往左，小于 `x` 往下；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    def findElement(self , mat: List[List[int]], n: int, m: int, x: int) -> List[int]:
        
        i, j = 0, m - 1
        while i < n and j >= 0:
            if mat[i][j] > x:
                j -= 1
            elif mat[i][j] < x:
                i += 1
            else:
                return [i, j]
        
        return [-1, -1]
```

</details>
