当前位置:网站首页>LeetCode:剑指 Offer 04. 二维数组中的查找
LeetCode:剑指 Offer 04. 二维数组中的查找
2022-07-06 08:44:00 【Bertil】
在一个 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
注意:本题与主站 240 题相同:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/
解题思路
1.首先定义出左下角的坐标,
2.然后从左下角元素开始遍历矩阵:若当前元素 > target,则上移一行;若当前元素 < target,则右移一列;若当前元素 = target,则直接返回true即可
3.最后通过上述循环遍历查找后,若未找到等于target的元素则直接返回false即可
代码
/** * @param {number[][]} matrix * @param {number} target * @return {boolean} */
var findNumberIn2DArray = function(matrix, target) {
if(!matrix.length) return false;
// 定义左下角的坐标
let [row, col] = [matrix.length - 1, 0];
const len = matrix[0].length;
// 坐标在矩阵内,就一直查找
while (row >= 0 && col <= len - 1) {
// item 表示当前元素
const item = matrix[row][col];
if (item === target) {
// 找到,返回true
return true;
} else if (item > target) {
// 太大了,上移一行
row--;
} else {
// 太小了,右移一列
col++;
}
}
return false;
};
边栏推荐
- China vanadium battery Market Research and future prospects report (2022 Edition)
- [MySQL] log
- torch建立的网络模型使用torchviz显示
- 软件卸载时遇到trying to use is on a network resource that is unavailable
- Detailed explanation of heap sorting
- China dihydrolaurenol market forecast and investment strategy report (2022 Edition)
- Visual implementation and inspection of visdom
- gcc动态库fPIC和fpic编译选项差异介绍
- 生成器参数传入参数
- sublime text中conda环境中plt.show无法弹出显示图片的问题
猜你喜欢
Simple use of promise in uniapp
2022.02.13 - NC002. sort
Excellent software testers have these abilities
可变长参数
Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
View computer devices in LAN
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
C语言深度解剖——C语言关键字
[brush questions] top101 must be brushed in the interview of niuke.com
Precise query of tree tree
随机推荐
poi追加写EXCEL文件
Function coritization
Simple use of promise in uniapp
Synchronized solves problems caused by sharing
win10系统中的截图,win+prtSc保存位置
Detailed explanation of heap sorting
2022.02.13 - NC002. sort
pytorch训练好的模型在加载和保存过程中的问题
Pointer advanced --- pointer array, array pointer
Purpose of computer F1-F12
Colorlog combined with logging to print colored logs
Sublime text using ctrl+b to run another program without closing other runs
【ROS】usb_cam相机标定
POI add write excel file
【ROS】usb_ Cam camera calibration
JVM quick start
Visual implementation and inspection of visdom
R language uses the principal function of psych package to perform principal component analysis on the specified data set. PCA performs data dimensionality reduction (input as correlation matrix), cus
Revit 二次开发 HOF 方式调用transaction
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform