当前位置:网站首页>剑指Offer04. 二维数组中的查找【中等】
剑指Offer04. 二维数组中的查找【中等】
2022-07-03 11:50:00 【伍六琪】
剑指 Offer 04. 二维数组中的查找 【中等】
题目描述
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 matrix 如下:
给定 target = 5,返回 true。
给定 target = 20,返回 false。
限制:
0 <= n <= 1000
0 <= m <= 1000
Java代码
暴力解法
简单粗暴两层遍历挨个找。
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
for(int i = 0;i<matrix.length;i++){
for(int j = 0;j<matrix[i].length;j++){
if(matrix[i][j]==target){
return true;
}
}
}
return false;
}
}
官方解法
从二维数组的右上角开始查找。如果当前元素等于目标值,则返回 true。如果当前元素大于目标值,则移到左边一列。如果当前元素小于目标值,则移到下边一行。
注意:可以证明这种方法不会错过目标值。如果当前元素大于目标值,说明当前元素的下边的所有元素都一定大于目标值,因此往下查找不可能找到目标值,往左查找可能找到目标值。如果当前元素小于目标值,说明当前元素的左边的所有元素都一定小于目标值,因此往左查找不可能找到目标值,往下查找可能找到目标值。
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row=0,column=matrix[0].length-1;
while(row<matrix.length&&column>=0){
if(matrix[row][column]==target){
return true;
}else if(matrix[row][column]<target){
row++;
}else{
column--;
}
}
return false;
}
}
补充思路:
关键是要能够想到,从二维数组的右上角开始遍历。
- 因为左上和右下角分别是数组的最大值和最小值,所有有两个方向可以同时选择,无法确定唯一。
- 而左下和右上就可以,就拿右上角举例,它是行的最大值,列的最小值。如果它比目标值小,就可以排除这一行数据,列+1(因为它已经是这一行的最大值,比目标值还小,说明这一行数据都太小了,不可能有目标值。故列+1舍弃。)
还有另一种思路就是:
- 在右上角看。这个矩阵其实就像是一个Binary Search Tree二叉查找树。
边栏推荐
- Jsup crawls Baidu Encyclopedia
- [combinatorics] permutation and combination (example of permutation and combination)
- Redis
- PHP export word method (phpword)
- (数据库提权——Redis)Redis未授权访问漏洞总结
- Qt+vtk+occt reading iges/step model
- 2.9 overview of databinding knowledge points
- Unicode查询的官方网站
- Quantitative calculation research
- (构造笔记)MIT reading部分学习心得
猜你喜欢
【mysql专项】读锁和写锁
Unicode encoding table download
Shutter widget: centerslice attribute
Download address and installation tutorial of vs2015
ES6新特性
Shutter: add gradient stroke to font
If you can't learn, you have to learn. Jetpack compose writes an im app (II)
AOSP ~ NTP (Network Time Protocol)
Qt+vtk+occt reading iges/step model
What is more elegant for flutter to log out and confirm again?
随机推荐
Shell: basic learning
lambda与匿名内部类的区别
Systemverilog-- OOP--对象的拷贝
02_ Lock the code, and don't let the "lock" become a worry
DEJA_ Vu3d - cesium feature set 053 underground mode effect
If you can't learn, you have to learn. Jetpack compose writes an im app (I)
Is it safe to open an account for online stock speculation? Who can answer
网络通讯之Socket-Tcp(一)
2.8 overview of ViewModel knowledge
225. Implement stack with queue
239. Sliding window maximum
Pki/ca and digital certificate
Itext7 uses iexternalsignature container for signature and signature verification
Use of QT OpenGL camera
145. Post order traversal of binary tree
Use of atomicinteger
Implement verification code verification
ES6 standard
Adult adult adult
Redis 笔记 01:入门篇