当前位置:网站首页>剑指Offer 04.二位数组中的查找 线性查找
剑指Offer 04.二位数组中的查找 线性查找
2022-08-02 03:33:00 【HotRabbit.】
题目
在一个 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/
- Related Topics
- 数组
- 二分查找
- 分治
- 矩阵
思路
之前在刷二分的题时,刷到过这道题,所以一开始就想着用二分做,结果发现其实就是暴力+二分的解法
突然想到从最左下角的元素开始判断,然后就写出来了~
题解
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix.length == 0){
return false;
}
int n = matrix.length - 1;
int m = 0;
while (n >= 0 && m <= matrix[0].length - 1){
if (matrix[n][m] == target){
return true;
}else if (matrix[n][m] < target){
m++;
}else {
n--;
}
}
return false;
}
}
边栏推荐
猜你喜欢
随机推荐
剑指Offer 34.二叉树中和为某一值的路径 dfs+回溯
【plang 1.4.6】Plang高级编程语言(发布)
【LeetCode】设计链表
剑指Offer 64.求1+2+...+n 递归+&&
2020 - AAAI - Image Inpainting论文导读《Learning to Incorporate Structure Knowledge for Image Inpainting》
2020 - AAAI - 图像修复 Image Inpainting论文导读 -《Region Normalization for Image Inpainting》
笔记本电脑充电问题
【LeetCode】链表相加 进位
GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片
2019 - ICCV - 图像修复 Image Inpainting 论文导读《StructureFlow: Image Inpainting via Structure-aware ~~》
USB3.0一致性测试方法
Host your own website with Vercel
读取FBX文件踩坑清单
LT9211芯片资料分享
LL(1)文法 :解决 if-else/if-else 产生式二义性问题
最第k大的数的一般性问题
【Popular Science Post】Detailed explanation of MDIO interface
C语言教程 - 制作单位转换器
所有子字符串中的元音 —— LeetCode - 2063
实现动态库(DLL)之间内存统一管理