---
# System prepended metadata

title: Leetcode 240. Search a 2D Matrix II
tags: [Matrix, Sort, Leetcode, Binary Search]

---

## 題解

### 逐行 Binary Search

利用 row 由小到大的特性，逐行搜索

```python=
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])

        def binary_search(nums: List[int]):
            nonlocal n,target
            left, right = 0, n - 1
            while left <= right:
                mid = left + (right - left) // 2
                if nums[mid] < target:
                    left = mid + 1
                elif nums[mid] > target:
                    right = mid - 1
                else:
                    return True
            return False
        
        for i in range(m):
            if binary_search(matrix[i]):
                return True
        
        return False
```

### Z字搜索法

利用 row cols 由小到大的特性搜索

```python=
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])
        x, y = 0, n - 1

        while x < m and y >= 0:
            if matrix[x][y] == target:
                return True
            elif matrix[x][y] > target:
                y -= 1
            elif matrix[x][y] < target:
                x += 1

        return False
```