当前位置:网站首页>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
边栏推荐
- Typescript31 - any type
- PHP 使用 PHPRedis 与 Predis
- When paying attention to the "Internet +" model, you usually only focus on the "Internet +" model itself
- Navicat data shows incomplete resolution
- 6-24 exploit-vnc password cracking
- Constructor of typescript35-class
- Named parameter implementation of JDBC PreparedStatement
- 创新项目实战之智能跟随机器人原理与代码实现
- AntPathMatcher使用
- Basic use of typescript34-class
猜你喜欢
Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion
第一次写对牛客的编程面试题:输入一个字符串,返回该字符串出现最多的字母
6-25漏洞利用-irc后门利用
字节给我狠狠上了一课:危机来的时候你连准备时间都没有...
Chengdu openGauss user group recruit!
Day116. Shangyitong: Details of appointment registration ※
Day115.尚医通:后台用户管理:用户锁定解锁、详情、认证列表审批
typescript34-class的基本使用
【服务器数据恢复】服务器Raid5阵列mdisk磁盘离线的数据恢复案例
5年自动化测试经验的一些感悟:做UI自动化一定要跨过这10个坑
随机推荐
fastjson详解
Pcie the inbound and outbound
typescript30 - any type
Named parameter implementation of JDBC PreparedStatement
The characteristics and principle of typescript29 - enumeration type
60种特征工程操作:使用自定义聚合函数【收藏】
【ORB_SLAM2】SetPose、UpdatePoseMatrices
Shell Beginners Final Chapter
飞桨助力航天宏图PIE-Engine地球科学引擎构建
For effective automated testing, these software testing tools must be collected!!!
Kubernetes — 核心资源对象 — 存储
【Brush the title】Family robbery
数据链路层的数据传输
力扣 1161. 最大层内元素和
字节给我狠狠上了一课:危机来的时候你连准备时间都没有...
成都openGauss用户组招募啦!
Navicat数据显示不完全的解决方法
typescript35-class的构造函数
6-24漏洞利用-vnc密码破解
去经营企业吧