leetcode-240-搜索二维矩阵②
2024-10-07 20:43:29
题目描述:
最佳方法:O(m+n) O(1)
class Solution:
def searchMatrix(self, matrix, target):
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
方法二:O(nlogn)*
class Solution:
def searchMatrix(self, matrix, target):
# an empty matrix obviously does not contain `target`
if not matrix:
return False def search_rec(left, up, right, down):
# this submatrix has no height or no width.
if left > right or up > down:
return False
# `target` is already larger than the largest element or smaller
# than the smallest element in this submatrix.
elif target < matrix[up][left] or target > matrix[down][right]:
return False mid = left + (right-left)//2 # Locate `row` such that matrix[row-1][mid] < target < matrix[row][mid]
row = up
while row <= down and matrix[row][mid] <= target:
if matrix[row][mid] == target:
return True
row += 1 return search_rec(left, row, mid-1, down) or search_rec(mid+1, up, right, row-1) return search_rec(0, 0, len(matrix[0])-1, len(matrix)-1)
最新文章
- POJ 1696 Space Ant(极角排序)
- PL/SQL连接查询数据报错时Dynamic Performance Tables not accessible
- ASP 调用dll(VB)及封装dll实例
- solr拼写检查代码逻辑
- 【QT相关】Qt Widgets Module
- VBA怎样统计同一类型的数据的总和
- BZOJ 3963: [WF2011]MachineWorks [CDQ分治 斜率优化DP]
- unity集成openinstall流程
- django 连接mangodb 操作
- 软件测试实验二----selenium、katalon、junit
- C# WebApi+Task+WebSocket实战项目演练(四)
- hadoop_spark伪分布式实验环境搭建和运行实例详细教程
- nginx入门二
- VSFTPD虚拟用户配置
- vue路由跳转的多种方式
- C++说明符和限定符
- Sophus VS2010编译不支持?C++11语法的缘故。那有没有不带C++11特性的Sophus版本呢?
- InputStream TO byte
- Java多线程具体解释
- HDU 5646