LeetCode 240. Search a 2D Matrix II
考点 | 难度 |
---|---|
Matrix | Medium |
题目
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.
思路
如果M[r][c]
小于target说明应该向下面找(同一行的左边和同一列上边都比target小)所以继续移动直到大于target然后向左移动再判断
直到移动到matrix左下角,如果找到了返回true,没有找到返回false
答案
class Solution:
def searchMatrix(self, matrix, target):
m, n = len(matrix), len(matrix) and len(matrix[0])
r, c = 0, n-1
while r < m and c >= 0:
if target > matrix[r][c]:
r += 1
elif target < matrix[r][c]:
c -= 1
else: return True
return False