当前位置:网站首页>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;
}
}
边栏推荐
- Flink_CDC construction and simple use
- Image fusion based on weighted 】 and pyramid image fusion with matlab code
- 云和恩墨:让商业数据库时代的价值在openGauss生态上持续繁荣
- 密码学的基础:X.690和对应的BER CER DER编码
- typescript33 - high-level overview of typescript
- 电商库存系统的防超卖和高并发扣减方案
- R语言使用cph函数和rcs函数构建限制性立方样条cox回归模型、使用anova函数进行方差分析通过p值确认指定连续变量和风险值HR之间是否存在非线性关系
- Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
- 『网易实习』周记(二)
- Can‘t connect to MySQL server on ‘localhost3306‘ (10061) 简洁明了的解决方法
猜你喜欢
A full set of common interview questions for software testing functional testing [open thinking questions] interview summary 4-3

力扣 1374. 生成每种字符都是奇数个的字符串

27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!

YGG 公会发展计划第 1 季总结

MySQL8 下载、启动、配置、验证

数据链路层的数据传输

Constructor of typescript35-class

typeof in typescript32-ts

哈希冲突和一致性哈希

YGG Guild Development Plan Season 1 Summary
随机推荐
Basic use of typescript34-class
哈希表
Flask gets post request parameters
HSDC和独立生成树相关
Kubernetes — Flannel
关于MySQL的数据插入(高级用法)
大话西游无法登陆解决
乱七八糟的网站
【图像融合】基于加权和金字塔实现图像融合附matlab代码
Day116. Shangyitong: Details of appointment registration ※
手写一个博客平台~第三天
Redis 持久化 - RDB 与 AOF
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
Constructor instance method of typescript36-class
一本适合职场新人的好书
Kubernetes — 核心资源对象 — Controller
有效进行自动化测试,这几个软件测试工具一定要收藏好!!!
fastjson详解
字节给我狠狠上了一课:危机来的时候你连准备时间都没有...
【刷题篇】打家劫舍