当前位置:网站首页>剑指 Offer 04. 二维数组中的查找
剑指 Offer 04. 二维数组中的查找
2022-06-25 12:19:00 【辞树 LingTree】
难度中等409收藏分享切换为英文接收动态反馈
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 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]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
限制:
0 <= n <= 1000
0 <= m <= 1000
今天遇到的一道比较有意思的题目,大概是在这样一个行和列对应有序的二维数组中,查找目标数字tar有没有出现过。暴力搜索的话,时间复杂度太高O(n*m)。
于是,我们换种思路,从右上角开始查找。i代表行号,j代表列号
1.如果二维数组中当前位置的数字恰好等于tar,查找成功。
2.如果二维数组中当前位置的数字小于tar,那只能是在下一行,所以i++。
3.如果二维数组中当前位置的数字大于tar,那只能是在左侧,所以j--。
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
int n = matrix.length;
if(n == 0) return false;
int m = matrix[0].length;
int pos = 0;
int i = 0, j = m-1;
while(i < n && j >= 0 && i >= 0 && j < m){
if(target == matrix[i][j]) return true;
if(target > matrix[i][j]) i++;
else j--;
}
return false;
}
}
最终,我们可以在时间复杂度为O(n+m)解决问题。
边栏推荐
- 架构师需要具备的能力
- 康威定律,作为架构师还不会灵活运用?
- Laravel echart statistical chart line chart
- Using CMD (command prompt) to install MySQL & configure the environment
- 词法陷阱(C)
- flutter 收到推送后自动消失问题
- Match regular with fixed format beginning and fixed end
- Koa 框架
- MySQL adds, modifies, and deletes table fields, field data types, and lengths (with various actual case statements)
- 更新pip&下载jupyter lab
猜你喜欢
随机推荐
You can't specify target table 'xxx' for update in from clause
Swagger document generated by node project API in vscode
地理空间搜索:kd树的实现原理
Wechat full-text search technology optimization
微信全文搜索技术优化
Draw the satellite sky map according to the azimuth and elevation of the satellite (QT Implementation)
CUDA error: unspecified launch failure
高性能负载均衡架构如何实现?
剑指 Offer II 028. 展平多级双向链表
线上服务应急攻关方法论
(4) Pyqt5 tutorial -- > Custom signal and slot (super winding...)
The drop-down box renders numbers instead of the corresponding text. How to deal with it
Why are databases cloud native?
利用cmd(命令提示符)安装mysql&&配置环境
架构师必备的七种能力
用include what you use拯救混乱的头文件
5 kinds of viewer for browser
Spoken English - weak reading
Optimal solution for cold start
(2) Pyqt5 tutorial -- > using qtdesigner to separate interface code









