当前位置:网站首页>LeetCode Brushing Diary: 74. Searching 2D Matrix
LeetCode Brushing Diary: 74. Searching 2D Matrix
2022-08-02 01:55:00 【light [email protected]】
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值.该矩阵具有如下特性:
每行中的整数从左到右按升序排列.
每行的第一个整数大于前一行的最后一个整数.
示例 1:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
示例 2:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
思路:
因为是有序的,So first arrange the last number of each line to compare with the target,Find out if the target is in the range of the current row,不在,then loop to the next line,直到找到为止,找到当前行,Then use a binary search algorithm to find if there is a target in that row.
题解:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int x = 0;
for (int i = 0; i < m; i++) {
if(matrix[i][n-1] >= target){
x = i;
break;
}
}
int start = 0, end = n-1;
while (start <= end){
int mid = (start + end)/2;
if(matrix[x][mid] == target){
return true;
}else if(matrix[x][mid] > target){
end = mid - 1;
}else {
start = mid + 1;
}
}
return false;
}
}
版权声明
本文为[light [email protected]~no trace]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020144011619.html
边栏推荐
- The ultra-large-scale industrial practical semantic segmentation dataset PSSL and pre-training model are open source!
- 百度、百图生科 | HelixFold-Single: 使用蛋白质语言模型作为替代进行无MSA蛋白质结构预测
- C语言之插入字符简单练习
- 【图像融合】基于加权和金字塔实现图像融合附matlab代码
- Kubernetes — Calico
- 电商库存系统的防超卖和高并发扣减方案
- 6-24漏洞利用-vnc密码破解
- Day115.尚医通:后台用户管理:用户锁定解锁、详情、认证列表审批
- 60种特征工程操作:使用自定义聚合函数【收藏】
- Yunhe Enmo: Let the value of the commercial database era continue to prosper in the openGauss ecosystem
猜你喜欢
Huawei's 5-year female test engineer resigns: what a painful realization...
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
6-24漏洞利用-vnc密码破解
typescript37-class的构造函数实例方法继承(extends)
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
Basic use of typescript34-class
HSDC和独立生成树相关
百度、百图生科 | HelixFold-Single: 使用蛋白质语言模型作为替代进行无MSA蛋白质结构预测
AOF重写
Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided
随机推荐
Redis cluster mode
¶Backtop 回到顶部 不生效
Shell Beginners Final Chapter
MySQL8 下载、启动、配置、验证
typeof in typescript32-ts
云和恩墨:让商业数据库时代的价值在openGauss生态上持续繁荣
typescript36-class的构造函数实例方法
Kubernetes — 网络流量模型
Use flex-wrap to wrap lines in flex layout
feign异常传递的两种方式 fallbackfactory和全局处理 获取服务端自定义异常
R语言使用cph函数和rcs函数构建限制性立方样条cox回归模型、使用anova函数进行方差分析通过p值确认指定连续变量和风险值HR之间是否存在非线性关系
MySQL优化策略
安全(2)
typescript37-class的构造函数实例方法继承(extends)
Detailed explanation of fastjson
Kubernetes之本地存储
Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
3.Bean的作用域与生命周期
Yunhe Enmo: Let the value of the commercial database era continue to prosper in the openGauss ecosystem
一本适合职场新人的好书