当前位置:网站首页>《剑指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)。
边栏推荐
- Numpy np.max和np.maximum实现relu函数
- Stm32hal library upgrades firmware based on flash analog U disk (detailed explanation)
- (database authorization - redis) summary of unauthorized access vulnerabilities in redis
- Cadence background color setting
- How to mix embedded MCU, arm and DSP?
- Repo ~ common commands
- phpcms 提示信息頁面跳轉showmessage
- 聊聊Flink框架中的状态管理机制
- Redis things
- typeScript
猜你喜欢

ASP.NET-酒店管理系統

STL教程9-容器元素深拷贝和浅拷贝问题

PHP基础

(database authorization - redis) summary of unauthorized access vulnerabilities in redis

Excel quick cross table copy and paste

STL教程10-容器共性和使用场景

Based on MCU, how to realize OTA differential upgrade with zero code and no development?

导师对帮助研究生顺利完成学业提出了20条劝告:第一,不要有度假休息的打算.....

外插散点数据

Intel 13th generation core flagship exposure, single core 5.5ghz
随机推荐
836. 合并集合(DAY 63)并查集
2022年湖南工学院ACM集训第二次周测题解
Internet socket (non) blocking write/read n bytes
[OBS] configFile in ini format of OBS
Some common terms
【学习笔记】dp 状态与转移
Uniapp implementation Click to load more
Phpcms prompt message page Jump showmessage
AI模型看看视频,就学会了玩《我的世界》:砍树、造箱子、制作石镐样样不差...
用了这么久线程池,你真的知道如何合理配置线程数吗?
Hongmeng fourth training
动态规划(区间dp)
STL教程10-容器共性和使用场景
Kibana~Kibana的安装和配置
Driver development based on I2C protocol
Visual Studio 2022下载及配置OpenCV4.5.5
[OBS] encapsulate the basic process of OBS acquisition
同事写了一个责任链模式,bug无数...
After using the thread pool for so long, do you really know how to reasonably configure the number of threads?
量化计算调研