leetcode-mid-sorting and searching - 240. Search a 2D Matrix II -NO
2024-09-08 03:52:06
mycode time limited
def searchMatrix(matrix, target):
def deal(data):
if not data:
return False
row = len(data)
col = len(data[0])
#print('row,col',row,col)
for r in range(row):
for c in range(col):
#print(r,c)
if data[r][c] == target:
return True
elif data[r][c] > target:
deal(data[r+1:][:c])
if deal(matrix) :return True
else:
return False
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]
]
searchMatrix(matrix, 5)
参考:
1、while循环中问题的关键是,如何不断缩小搜索的范围? -- 从右上角or左下角开始是最好的,因为两个方向的变化是一个变大一个变小
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
row, col = 0, cols - 1
while True:
if row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else:
col -= 1
else:
return False
2、巧用pyhton
#暴力方法
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
return any(target in row for row in matrix)
最新文章
- Mysql Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation &#39;=&#39;
- Windows server用好windows server backup,发挥个人电脑该有的系统还原功能
- 【MYSQL】update/delete/select语句中的子查询
- 【Unique Binary Search Trees II】cpp
- MyBatis对不同数据库的主键生成策略
- nodejs框架express4.x 学习--安装篇
- ICE-3.5.1-错误记录
- POJ 2115 模线性方程 ax=b(mod n)
- 如何有效抓取SQL Server的BLOCKING信息
- HDU4893:Wow! Such Sequence!(段树lazy)
- Bourn Again Shell编程
- quartus2中FPGA管脚分配保存方法(转)
- 算法工程师:双非渣硕是如何获得百度、京东双SP
- Python与R的区别和联系
- 分析easyswoole3.0源码,协程连接池(五)
- liunx学习笔记(一:常用命令)
- 复制vmware主机修改网卡
- 使ipconfig命令结果更整洁
- 内置数据结构(tuple)
- this指向 - Node环境
热门文章
- Action获取请求参数的3中方式
- 表格强制换行 table-layout:fixed
- Python笔试面试题目及答案
- mybatis返回map结果集
- windows2008R2下安装sqlserver2008R2时,点setup.exe应用程序无法打开错误代码0xc0150004
- Java学习01-使用maven插件tomcat搭建web maven项目
- Tensort之uff
- php判断变量是否为数字is_numeric()
- Jsoup抓取网页数据完成一个简易的Android新闻APP
- python中导入from appium import webdriver时报错:ModuleNotFoundError: No module named &#39;appium&#39;