Subject description:
Prepared by an efficient algorithm to determine the mxn matrix, the presence or absence of a target value. This matrix has the following characteristics:
An integer of from left to right in each row in ascending order.
The first integer is greater than the last row of each integer previous row.
Example 1:
Input:
Matrix = [
[2,. 5,. 6,. 9],
[13 is, 14,. 17,. 19],
[25, 26 is, 27, 28]
]
target =. 6
Output: true
Example 2:
Input:
Matrix = [
[2,. 5,. 6,. 9],
[13 is, 14,. 17,. 19],
[25, 26 is, 27, 28]
]
target = 15
Output: false
Problem solution ideas: Find a binary thinking method to find the target, the first division of the middle value mid, because the topics given mxn is a two-dimensional matrix, the matrix of fact, we can be understood as a nested list, in the form of [[0,0,0], [0,0,0], [0,0,0]], so since the values for m, n becomes obvious, are the lengths of two lists, and so on since mid value can be determined. python code to achieve the following:
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix == None or len (matrix) == 0: # matrix is first determined whether empty
return False
row = len(matrix)
col = len (matrix [0])
start = 0
end = row * col - 1
while start <= end:
mid = start + (end - start ) / 2 # As mid why not (start + end) / 2 may refer this blog
if matrix[mid / col][mid % col] == target:
return True
if matrix[mid / col][mid % col] > target:
end = mid - 1
else:
start = mid + 1
return False