题目描述:
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
示例 1:
输入:
matrix = [
[2, 5, 6, 9],
[13, 14, 17, 19],
[25, 26, 27, 28]
]
target = 6
输出: true
示例2:
输入:
matrix = [
[2, 5, 6, 9],
[13, 14, 17, 19],
[25, 26, 27, 28]
]
target = 15
输出: false
题解思路:用二分查找法的思路来查找目标值,首先划分中间值mid,因为题目给定的是一个 m x n的二维矩阵,实际上我们可以将该矩阵理解为一个嵌套的list,形式为[[0,0,0,],[0,0,0],[0,0,0]],如此以来m、n的值就很明显了,分别是两个列表的长度,如此以来就可以确定mid值。python代码实现如下:
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: #首先判断矩阵是否为空
return False
row = len(matrix)
col = len(matrix[0])
start = 0
end = row * col - 1
while start <= end:
mid = start + (end - start) / 2 #至于mid为啥不是(start+end)/2 可参考这篇博客
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