Problem: 74. 搜索二维矩阵
思路 & 解题方法
可以二分一次,也可以二分两次。
复杂度
时间复杂度:
添加时间复杂度, 示例: O ( l o g n + l o g m ) O(logn + logm) O(logn+logm)
空间复杂度:文章来源:https://www.toymoban.com/news/detail-786784.html
添加空间复杂度, 示例: O ( 1 ) O(1) O(1)文章来源地址https://www.toymoban.com/news/detail-786784.html
二分两次
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
top, but = 0, m - 1
while top < but:
mid = (top + but) // 2
if matrix[mid][-1] < target:
top = mid + 1
elif matrix[mid][-1] >= target:
but = mid
if but >= 0 and but < m:
left, right = 0, n - 1
l = matrix[but]
while left <= right:
mid = (left + right) // 2
if l[mid] > target:
right = mid - 1
elif l[mid] < target:
left = mid + 1
else:
return True
return False
二分一次
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
for l in matrix:
if l[-1] < target:
continue
else:
left, right = 0, n - 1
while left <= right:
mid = (left + right) // 2
if l[mid] < target:
left = mid + 1
elif l[mid] > target:
right = mid - 1
else:
return True
break
return False
到了这里,关于搜索二维矩阵【二分】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!