2

#yyds干货盘点# 面试必刷TOP101:二维数组中的查找

 1 year ago
source link: https://blog.51cto.com/u_15488507/5567612
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# 面试必刷TOP101:二维数组中的查找

原创

97的风 2022-08-11 15:57:50 博主文章分类:面试题 ©著作权

文章标签 二维数组 数据 一维数组 文章分类 Java 编程语言 阅读数277

1.简述:

在一个二维数组array中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]

给定 target = 7,返回 true。

给定 target = 3,返回 false。

数据范围:矩阵的长宽满足  , 矩阵中的值满足 进阶:空间复杂度  ,时间复杂度 

7,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
存在7,返回true
1,[[2]]
false
3,[[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
false
不存在3,返回false

2.代码实现:

public class Solution {
public boolean Find(int target, int [][] array) {
//优先判断特殊
if(array.length == 0)
return false;
int n = array.length;
if(array[0].length == 0)
return false;
int m = array[0].length;
//从最左下角的元素开始往左或往上
for(int i = n - 1, j = 0; i >= 0 && j < m; ){
//元素较大,往上走
if(array[i][j] > target)
i--;
//元素较小,往右走
else if(array[i][j] < target)
j++;
else
return true;
}
return false;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK