当前位置:网站首页>Finding a 2D Array
Finding a 2D Array
2022-07-30 00:17:00 【Ryuzaki Liuhe】
题目:
在一个 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.
分析:
从左下角开始查找,Subtract the number of rows if the current number is greater than the target value1,The number of columns is added if the current number is less than the target value1,until the target value is found.
代码:
public class FindNumberIn2DArray {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
//Remember not to forget this judgment on the array
if(matrix == null || matrix.length <= 0 || matrix[0].length <= 0){
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
//Determine the position of the lower left corner
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;
}
}
边栏推荐
- At the age of 29, I was fired from a functional test. Can't find a job after 2 months of interviews?
- NumPy(一)
- Replace the executable file glibc version of the one
- He used to cells harvested trypsin & release procedure
- 【集训DAY16】ALFA【凸壳】【计算几何】
- The difference and usage of call, apply and bind
- 单片机开发之基本并行I/O口
- ZLMediaKit源码分析 - WebRtc连接迁移
- “灯塔工厂”的中国路径:智造从点到面铺开
- Adaptive feature fusion pyramid network for multi-classes agriculturalpest detection
猜你喜欢
Genesis与Axis Ventures互动密切
多商户商城系统功能拆解18讲-平台端商家售后
更换可执行文件glibc版本的某一次挣扎
Worthington木瓜蛋白酶&胰凝乳蛋白酶&脱氧核糖核酸酶 I
Some personal understandings about MySQL indexes (partially refer to MySQL45 lectures)
CesiumJS ^ source read [0] 2022 - article directory and source engineering structure
Sentinel入门
EA & UML Sun Arch - State Diagram :: Redraw Button State Diagram
旋转数组的最小数字
Worthington用于细胞收获的胰蛋白酶&细胞释放程序
随机推荐
循环神经网络(RNN)
Chinese semantic matching
EA&UML日拱一卒-多任务编程超入门-(8)多任务安全的数据类
EA&UML日拱一卒-多任务编程超入门-(2)进程和线程
vim相关介绍(三)
Reading notes. This is the psychology: see through the essence of the pseudo psychology (version 10)"
Worthington Papain & Chymotrypsin & DNase I
WeChat developer tools set the tab size to 2
The go language (functions, closures, defer, panic/recover, recursion, structure, json serialization and deserialization)
Adaptive feature fusion pyramid network for multi-classes agriculturalpest detection
2022杭电多校第三场 Two Permutations (dp, 哈希)
基于TNEWS‘ 今日头条中文新闻(短文本)分类
Expansion of Parallel I/O Port in Single Chip Microcomputer Development
NumPy(二)
微信开发者工具设置制表符大小为2
UE4 制作十字准心+后坐力
The strongest JVM in the whole network is coming!(Extreme Collector's Edition)
转发和重定向的区别及使用场景
I.MX6U-驱动开发-3-新字符驱动
EA&UML日拱一卒-状态图::重画按钮状态图