题目
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 from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
思路
从矩阵的最右端元素开始考虑,如果它比所求要大,那么在当前行查找即可。否则,进入下一行。
代码
class Solution(object):
def binarySearch(self, nums, l, r, target):
if l > r:
return False
m = l + (r-l)/2
if nums[m] == target:
return True
elif nums[m] > target:
return self.binarySearch(nums, l, m-1, target)
else:
return self.binarySearch(nums, m+1, r, target)
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix==None or len(matrix)==0:
return False
m = len(matrix)
n = len(matrix[0])
i = 0
while i < m:
if matrix[i][n-1] == target:
return True
elif matrix[i][n-1] > target:
return self.binarySearch(matrix[i], 0, n-1, target)
else:
i += 1
return False