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.
Example:
Consider the following matrix:
[ [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] ]
Given target = 5
, return true
.
Given target = 20
, return false
.
LeetCode:链接
和LeetCode74:Search a 2D Matrix做法相似。
第一种方法:和剑指Offer_编程题01:二维数组中的查找是一样的。所以74和220题没有区别。
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
row = len(matrix)
col = len(matrix[0])
i = 0
j = col - 1
while i < row and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
j -= 1
else:
i += 1
return False
第二种方法:二分法。根据矩阵的第一列确定值可能所在的行的范围,确定了值可能在的行的范围后,逐行在进行二分查找目标值,这样就将问题降到一维上来了。
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0 or matrix == [[]]:
return False
row = len(matrix)
col = len(matrix[0])
low = 0
high = row - 1
# 二分查找目标值可能所在行的上限
while low <= high:
mid = (low + high) // 2
if target == matrix[mid][0]:
return True
elif target > matrix[mid][0]:
low = mid + 1
else:
high = mid - 1
if low == 0:
return False
# 对每一行进行二分查找 边界值是low
for i in range(low):
l = 0
r = col - 1
while l <= r:
mid = (l + r) // 2
if matrix[i][mid] == target:
print(i, mid)
return True
elif matrix[i][mid] > target:
r = mid - 1
else:
l = mid + 1
return False