# 240. Search a 2D Matrix II 搜索二维矩阵 II

@TOC

## # 题目描述

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

1. Integers in each row are sorted in ascending from left to right.
2. Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following 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]
]
``````

Given target = 5, return true.

Given target = 20, return false.

## # 解题方法

74. Search a 2D Matrixopen in new window完全一样的代码就A了。。我都蒙的。

Python代码：

``````class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
row, col = 0, cols - 1
while True:
if row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else:
col -= 1
else:
return False
``````

C++代码如下：

``````class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0 || matrix[0].size() == 0) return false;
const int M = matrix.size(), N = matrix[0].size();
int i = M - 1, j = 0;
while (i >= 0 && j < N) {
if (matrix[i][j] == target) {
return true;
} else if (matrix[i][j] < target) {
++j;
} else {
--i;
}
}
return false;
}
};
``````

``````class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
return any(target in row for row in matrix)
``````

## # 日期

2018 年 3 月 6 日 2019 年 1 月 7 日 —— 新的一周开始啦啦啊