在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
`public class Solution {
public boolean Find(int [][] array,int target) {
for(int i=0;i<array.length;i++){
for(int j=0;j<array[0].length;j++){
if(array[i][j]==target) return true;
}
}
return false;
}
}`
其中的时间复杂度为O(n^2)
public static boolean Find2(int[][] a,int target){
int column = a[0].length-1;//列
int row = 0;//行
int hang = a.length;
while(row<hang&&column>=0){
System.out.println(row+"--"+column);
if(target>a[row][column]){
row++;
}else if(target<a[row][column]){
column--;
}else{
return true;
}
}
return false;
}
这样改完之后时间复杂度就降低了不少。
二维数组查找优化
本文介绍了一种在递增排序的二维数组中查找特定整数的方法,并对比了两种不同实现方式的时间复杂度。一种方法采用逐行遍历的方式,时间复杂度为O(n^2);另一种方法利用数组特性进行优化,将时间复杂度降低。

被折叠的 条评论
为什么被折叠?



