problem
Write an efficient algorithm that searches for a value in an m x n
matrix. This matrix has the following properties:Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
solution
这个问题可以看做是二分查找的拓展,都是从中间找到一个点,与之相比,然后排除一部分不可能的点。
下面是一个递归的解法,时间复杂度为
O(m+n)
问题:有没有更好的解法?
如果每次比较的是最中间的元素的话,每次可以至少删除1/4个元素,也就是
T(n)=3T(n/4)+O(1)
,使用主定理可得
logba=log43>0
,所以
T(n)=Θ((m+n)log43)
,使用递归树也可以得到同样的值。
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
def find(matrix, ms, me, ns, ne, t):
if ms > me or ns >ne:
return False
# print(matrix[ms][ne])
if t == matrix[ms][ne]:
return True
elif t > matrix[ms][ne]:
return find(matrix, ms+1, me, ns, ne, t)
else:
return find(matrix, ms, me, ns, ne-1, t)
return find(matrix, 0, m-1, 0, n-1, target)
仿照这个思路可以写成循环的形式,性能会提升一些。