当前位置:网站首页>剑指 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)解决问题。
边栏推荐
- Matlab simulation of m-sequence
- 剑指 Offer II 032. 有效的变位词
- 2021-09-30
- JS picture switching (simple and practical)
- First acquaintance with CANopen
- QT TCP UDP network communication < theory >
- 剑指Offer 第 2 天链表(简单)
- JS function exercises
- 量化交易之回测篇 - 期货CTA策略策略(TQZFutureRenkoWaveStrategy)
- JSTL tag: fmt:formatdate tag format Chinese standard time or timestamp
猜你喜欢

C program linking SQLSERVER database: instance failed

It is extraordinary to make a move, which is very Oracle!

康威定律,作为架构师还不会灵活运用?

2021-09-22

2021-09-28

Parse JSON format data and save it to entity class

High performance + million level Excel data import and export
![[visio] solving the fuzzy problem of parallelogram in word](/img/04/8a1de2983d648e67f823b5d973c003.png)
[visio] solving the fuzzy problem of parallelogram in word

Draw the satellite sky map according to the azimuth and elevation of the satellite (QT Implementation)

Idea2017 how to set not to automatically open a project at startup
随机推荐
剑指 Offer II 029. 排序的循环链表
Match regular with fixed format beginning and fixed end
Matlab simulation of m-sequence
(2) Pyqt5 tutorial -- > using qtdesigner to separate interface code
又是被Visdom搞崩溃的一夜
Elemntui's select+tree implements the search function
地理空间搜索:kd树的实现原理
Jenkins Pipeline使用
模块五(微博评论)
It is extraordinary to make a move, which is very Oracle!
浏览器的5种观察器
JSTL tag: fmt:formatdate tag format Chinese standard time or timestamp
2021-09-22
Possible problems when idea encounters errors occurred while compiling module (solved)
Go novice exploration road 1
Geospatial search: implementation principle of KD tree
nacos无法修改配置文件Mysql8.0的解决方法
Swagger document generated by node project API in vscode
Differences between JS and JQ operation objects
(3) Pyqt5 tutorial -- > signal and slot preliminary test