当前位置:网站首页>LeetCode刷题日记:74. 搜索二维矩阵
LeetCode刷题日记:74. 搜索二维矩阵
2022-08-02 01:44:00 【淡墨@~无痕】
编写一个高效的算法来判断 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
思路:
因为是有序的,所以先编排每一行的最后一个数字与目标对比,找出目标是否在当前行的范围,不在,那就循环到下一行,直到找到为止,找到当前行,那就使用二分查找算法查找该行中是否存在目标。
题解:
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;
}
}
边栏推荐
猜你喜欢
软件测试功能测试全套常见面试题【开放性思维题】面试总结4-3
YGG Guild Development Plan Season 1 Summary
The characteristics and principle of typescript29 - enumeration type
Win Go开发包安装配置、GoLand配置
typescript30 - any type
成都openGauss用户组招募啦!
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
typescript35-class的构造函数
MySQL8 下载、启动、配置、验证
Flink_CDC搭建及简单使用
随机推荐
PHP直播源码实现简单弹幕效果的相关代码
C语言之插入字符简单练习
pcie inbound和outbound关系
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
创新项目实战之智能跟随机器人原理与代码实现
力扣 1374. 生成每种字符都是奇数个的字符串
Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
乱七八糟的网站
MySQL——增删查改操作
有效进行自动化测试,这几个软件测试工具一定要收藏好!!!
【图像融合】基于加权和金字塔实现图像融合附matlab代码
飞桨助力航天宏图PIE-Engine地球科学引擎构建
Image fusion based on weighted 】 and pyramid image fusion with matlab code
当关注「互联网+」模式的时候,通常仅仅只是在关注「互联网+」模式本身
手写博客平台~第二天
牛顿定理和相关推论
Kubernetes — 网络流量模型
Flex layout in detail
Typescript31 - any type
NFT到底有哪些实际用途?