当前位置:网站首页>《剑指offer 04》二维数组查找
《剑指offer 04》二维数组查找
2022-07-03 11:02:00 【爱敲代码的小邢~】
《剑指offer 04》二维数组查找
【LeetCode链接】
【题目】
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
[
[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
【思路】🧐
首先想到的思路就是遍历数组,找到就返回true,找不到就返回false,这样的时间复杂度为O(N*M),那有没有更优的方法呢?
由题得,每一行都是递增的,每一列也都是递增的,所以我们会萌生二分搜索的思想。
那怎么在二维数组中运用二分的思想呢?
我们知道,在一位数组中二分的核心就是找到中间下标mid,在二维数组中,这个mid就是每两行中前一行的最后一个元素的下标。
为什么呢?
因为我们是否在本行查找或是到下一行查找就取决于target与改下标对于元素值的大小关系,若target小于该元素,则我们在本行找;若target大于该元素,则我们到下面的行去找。
【步骤】

这里要注意 matrix.size() 是行数,matrix[0].size() 是列数。
【代码】
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if (matrix.empty() == true)//如果矩阵为空,则一定没有target
return false;
int i = 0;
int j = matrix[0].size()-1;
while (i<matrix.size() && j >= 0)
{
if (matrix[i][j] == target){
return true;
}
if (matrix[i][j]>target){
j--;
}
else{
i++;
}
}
return false;
}
};
【时间复杂度】
该算法最坏情况就是走到左下位置,故时间复杂度为O(N+M)。
边栏推荐
- 错排问题 (抽奖,发邮件)
- The manuscript will be revised for release tonight. But, still stuck here, maybe what you need is a paragraph.
- Visual Studio 2022下载及配置OpenCV4.5.5
- Leetcode 46: full arrangement
- VPP three-layer network interconnection configuration
- Viewing binary bin files with notepad++ editor
- Spl06-007 air pressure sensor (example of barometer)
- Using onvif protocol to operate the device
- VS2015的下载地址和安装教程
- 软件测试周刊(第78期):你对未来越有信心,你对现在越有耐心。
猜你喜欢

Spl06-007 air pressure sensor (example of barometer)

MATLAB extrait les données numériques d'un fichier txt irrégulier (simple et pratique)

2022 东北四省赛 VP记录/补题

一文搞懂Go语言Context

Use typora to draw flow chart, sequence diagram, sequence diagram, Gantt chart, etc. for detailed explanation

活动预告 | 直播行业“内卷”,以产品力拉动新的数据增长点

GCC compilation process and dynamic link library and static link library

PHP Basics

Hongmeng fourth training

Processes and threads
随机推荐
asyncio 警告 DeprecationWarning: There is no current event loop
Nestjs配置服务,配置Cookie和Session
一些常用术语
R language ggplot2 visualization: gganimate package creates dynamic line graph animation (GIF) and uses transition_ The reveal function displays data step by step along a given dimension in the animat
Analysis of EPS electric steering system
R language uses the aggregate function to calculate the mean value (sum) of dataframe data grouping aggregation without setting na The result of RM calculation. If the group contains the missing value
typeScript
Xml的(DTD,xml解析,xml建模)
phpcms 提示信息頁面跳轉showmessage
Gut | 香港中文大学于君组揭示吸烟改变肠道菌群并促进结直肠癌(不要吸烟)
Programmers' entrepreneurial trap: taking private jobs
Visual Studio 2022下载及配置OpenCV4.5.5
鸿蒙第三次培训(项目实训)
Arctangent entropy: the latest SCI paper in July 2022
Web security summary
导师对帮助研究生顺利完成学业提出了20条劝告:第一,不要有度假休息的打算.....
JGG专刊征稿:时空组学
Web安全总结
C language log base zlog basic use
鸿蒙第四次培训