当前位置:网站首页>二维数组的查找
二维数组的查找
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;
}
}

边栏推荐
- 【分层强化学习】HAC源码解读
- Elephant Swap: Provide arbitrage space in the crypto market with ePLATO
- C陷阱与缺陷 第3章 语义“陷阱” 3.10 为函数main提供返回值
- 2022年企业直播行业发展洞察
- He cell separation technology 丨 basic primary cell separation methods and materials
- 消息中间件解析 | 如何正确理解软件应用系统中关于系统通信的那些事?
- Worthington Dissociation Enzymes: Collagenase and Four Basic Profiles
- 随便记记第二周
- The basic parallel I/O port of single chip microcomputer development
- UE4 makes crosshair + recoil
猜你喜欢

2022年企业直播行业发展洞察

Worthington解离酶:胰蛋白酶及常见问题
Docker install MySQL8.0

消息中间件解析 | 如何正确理解软件应用系统中关于系统通信的那些事?

Since the media how to write a short video title?Three hot style title, let your video gain more traffic

Introduction to Worthington Elastase & Hyaluronidase

BEVDetNet: Bird's Eye View LiDAR Point Cloud based Real-time 3D Object Detection for Autonomous Drivi

At the age of 29, I was fired from a functional test. Can't find a job after 2 months of interviews?

Worthington Dissociation Enzymes: Collagenase and Four Basic Profiles

jenkins搭建部署详细步骤
随机推荐
Worthington用于细胞收获的胰蛋白酶&细胞释放程序
新闻文本分类
【集训DAY16】ALFA【凸壳】【计算几何】
经典论文-SqueezeNet论文及实践
综合练习——三子棋小游戏
C陷阱与缺陷 第4章 链接 4.5 检查外部类型
利用热点事件来创作软文的3大技巧?自媒体人必看
Toutiao We-Media Operation: How to Gain 500+ Fans in Toutiao Today?
Unity Addressables
Worthington弹性蛋白酶&透明质酸酶简介
Worthington解离酶:胶原酶及四个基本概况
Adaptive feature fusion pyramid network for multi-classes agriculturalpest detection
Reading notes. This is the psychology: see through the essence of the pseudo psychology (version 10)"
新媒体运营必备的4个热点查询网
Worthington酶促细胞收获&细胞粘附和收获
Docker install MySQL8.0
QTableWidget使用示例
全网最强 JVM 来袭!(至尊典藏版)
2022年企业直播行业发展洞察
更换可执行文件glibc版本的某一次挣扎