Search a 2D Matrix II

Search a 2D Matrix II

zip Version - 52ms

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
for line in zip(*matrix):
if target in line:
return True
return False

Another Version - 48ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix: return False
m, n = len(matrix), len(matrix[0])
row, col = 0, n - 1
while row < m and col >= 0:
if matrix[row][col] == target:
return True
if matrix[row][col] > target:
col -= 1
else:
row += 1
return False

test code

1
2
3
4
5
6
7
8
9
In [27]: s = Solution(); t = s.searchMatrix(m, 20)
In [28]: t
Out[28]: False
In [29]: s = Solution(); t = s.searchMatrix(m, 5)
In [30]: t
Out[30]: True

leet code