当前位置:网站首页>二维数组的查找
二维数组的查找
2022-07-30 00:09:00 【龙崎流河】
题目:
在一个 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。
分析:
从左下角开始查找,如果当前数字比目标值大就行数减1,如果当前数字比目标值小则列数加1,直到找到目标值为止。
代码:
public class FindNumberIn2DArray {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
//这个对数组的判断记得不要忘记
if(matrix == null || matrix.length <= 0 || matrix[0].length <= 0){
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
//确定左下角位置
int row = rows-1;
int col = 0;
while (row >= 0 && col <= cols - 1){
if (target > matrix[row][col]){
col++;
}else if(target < matrix[row][col]){
row--;
}else {
return true;
}
}
return false;
}
}

边栏推荐
- 绘制几何图形
- call、apply 以及 bind 的区别和用法
- Elephant Swap:借助ePLATO提供加密市场的套利空间
- ZLMediaKit源码学习——UDP
- 【集训DAY18】有趣的交换【模拟】【数学】
- How do we-media people create explosive articles?These 3 types of articles are most likely to explode
- The strongest JVM in the whole network is coming!(Extreme Collector's Edition)
- Worthington弹性蛋白酶&透明质酸酶简介
- Go日志库——logrus
- From the perspective: the interviewer interview function test engineer mainly inspects what ability?
猜你喜欢

The strongest JVM in the whole network is coming!(Extreme Collector's Edition)

Codeforces Round #805 (Div. 3)总结

Worthington's tried and tested cell isolation system protocols

Worthington dissociating enzyme: detailed analysis of neutral protease (dispase)

多商户商城系统功能拆解18讲-平台端商家售后

月薪15k的阿里测试岗,面试原来这么简单

Worthington木瓜蛋白酶&胰凝乳蛋白酶&脱氧核糖核酸酶 I
综合练习——三子棋小游戏

Low dropout linear regulator MPQ2013A-AEC1 brand MPS domestic replacement

管理区解耦架构见过吗?能帮客户解决大难题的
随机推荐
【云原生Kubernetes】二进制搭建Kubernetes集群(中)——部署node节点
18 Lectures on Disassembly of Multi-merchant Mall System Functions
Worthington Dissociation Enzymes: Trypsin and Frequently Asked Questions
YoloV5数据集自动划分训练集、验证集、测试集
shell编写规范和变量
Music theory & guitar skills
He used to cells harvested trypsin & release procedure
ZLMediaKit源码分析 - WebRtc连接迁移
"The lighthouse factory" of China path: smart roll out from point to surface
随便记记第二周
SQL Server、MySQL主从搭建,EF Core读写分离代码实现
新闻文本分类
单片机开发之基本并行I/O口
Decision tree principle and code implementation
2022/7/29 考试总结
Codeforces Round #805 (Div. 3)总结
Elephant Swap:借助ePLATO提供加密市场的套利空间
Adaptive feature fusion pyramid network for multi-classes agriculturalpest detection
“ 我是一名阿里在职9年软件测试工程师,我的经历也许能帮到处于迷茫期的你 ”
机器人的运动范围