# leetcode 240. Search a 2D Matrix II（python）

### 描述

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

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

Example 1:

``````Input: 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]], target = 5
Output: true

Example 2:

``````Input: 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]], target = 20
Output: false

Example 3:

Note:

``````m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-10^9 <= matrix[i][j] <= 10^9
All the integers in each row are sorted in ascending order.
All the integers in each column are sorted in ascending order.
-10^9 <= target <= 10^9

### 解析

• 每行中的整数从左到右升序排序。
• 每列中的整数从上到下按升序排序。

### 解答

``````class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
M = len(matrix)
N = len(matrix[0])
i, j = 0, N - 1
while i < M and j >= 0:
if matrix[i][j] == target:
return True
if matrix[i][j] < target:
i += 1
elif matrix[i][j] > target:
j -= 1
return False

### 运行结果

``````Runtime: 211 ms, faster than 45.36% of Python online submissions for Search a 2D Matrix II.
Memory Usage: 19.5 MB, less than 70.32% of Python online submissions for Search a 2D Matrix II.

### 原题链接

leetcode.com/problems/se…