LintCode Q38 Search a 2D Matrix II in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2016年12月11日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
"""
@param matrix: An list of lists of integers
@param target: An integer you want to search in matrix
@return: An integer indicates the total occurrence of target in the given matrix
"""
def searchMatrix(self, matrix, target):
# write your code here
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
m = len(matrix) - 1
n = len(matrix[0]) - 1
if target < matrix[0][0] or target > matrix[m][n]:
return 0
count = 0
# from bottom left to top right
row = m
col = 0
while row >= 0 and col <= n:
if matrix[row][col] < target:
col += 1
elif matrix[row][col] > target:
row -= 1
else:
count += 1
col += 1
row -= 1
return count
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。