240._search_a_2d_matrix_ii.md 1.2 KB
Newer Older
1
### 240. Search a 2D Matrix II
K
KEQI HUANG 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40



题目:
<https://leetcode.com/problems/search-a-2d-matrix-ii/>


难度:
Medium

思路:

每行,每列都是sorted

但是比较好的策略是从右上角开始搜索,比如这样:

```
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]
]

m, n =  0, col - 1
更新策略:
 matrix[m][n] < target: 那么这一行到从左走到此都会小于target,row+1 ,往下走
 matrix[m][n] > target:  那么这一列往下走都会大于target,col - 1,往左走
 否则找到
```

时间复杂度O(max(M,N)),因为每次都会往下或者往左走


用的算法是Saddleback



41
```python
K
KEQI HUANG 已提交
42 43 44 45 46 47 48 49
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
50
            return False
K
KEQI HUANG 已提交
51
        row = len(matrix)
52 53
        col = len(matrix[0]) if row else 0 
        m, n = 0, col - 1
K
KEQI HUANG 已提交
54
        while m < row and n >= 0:
55 56 57 58 59 60
            if matrix[m][n] < target:
                m += 1
            elif matrix[m][n] > target:
                n -= 1
            else:
                return True
K
KEQI HUANG 已提交
61 62
        return False

63
```