[LeetCode]Search a 2D Matrix II 搜索二维矩阵2
Search a 2D Matrix II
二分搜索
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
if target < matrix[0][0] or target > matrix[-1][-1]:
return False
row, col = len(matrix)-1, 0
while True:
if matrix[row][col] > target:
row -= 1
elif matrix[row][col] < target:
col += 1
else:
return True
if row < 0 or col >= len(matrix[0]):
return False
return False
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
if target < matrix[0][0] or target > matrix[-1][-1]:
return False
rol = len(matrix[0])-1
for row in matrix:
while rol >=0 and row[rol] > target:
rol -= 1
if row[rol] == target:
return True
return False
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法

浙公网安备 33010602011771号