Search a 2D Matrix II
[
[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]
]题目大意:
解题思路:
源码分析
Lintcode 另一种变形:出现次数
Last updated
[
[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]
]Last updated
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix == [] or matrix[0] == [[]]:
return False
row = len(matrix)
col = len(matrix[0])
# 从左下角开始
i = row - 1
j = 0
while i >= 0 and j <= col - 1:
if target == matrix[i][j]:
return True
elif target < matrix[i][j]:
i -= 1
else:
j += 1
return Falseclass 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 matrix==[] or matrix == [[]]:
return 0
row = len(matrix)
column = len(matrix[0])
x = row-1
y = 0
result=0
while x>=0 and y<=column-1:
if matrix[x][y] > target:
x-=1
elif matrix[x][y] < target:
y+=1
else:
result += 1
y+=1
x-=1
return result