在行列都排好的矩阵中找指定的数字。
这道在《剑指offer》中也有一道类似的,因为行列都是排好序的,所以可以从二维数组的右上角或者左下角开始比较。
以右上角为例,如果数组值大于指定的数字,那么,这个数字一定大于这一行所有的值;如果数组值小于这个数字,那么这个数字一定小于这一列所有的值。
代码如下:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main{
public static String isInMatrix(int[][] arr, int n, int m, int k){
int i = 0;
int j = m - 1;
while(i < n && j > -1){
if (arr[i][j] == k)
return "Yes";
if(arr[i][j] > k)
j--;
else
i++;
}
return "No";
}
public static void main(String[]args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] arguements = reader.readLine().split(" ");
int n = arguements[0].charAt(0) - '0';
int m = arguements[1].charAt(0) - '0';
int k = arguements[2].charAt(0) - '0';
int[][] arr = new int[n][m];
String[] elements;
for (int i = 0; i < n; i++){
elements = reader.readLine().split(" ");
for(int j = 0; j < m; j++){
arr[i][j] = elements[j].charAt(0) - '0';
}
}
String result = isInMatrix(arr, n, m, k);
System.out.println(result);
}
}
这里我有一个不太理解的地方,就是,把String转换为int的时候,最开始我使用的是Integer.parseInt,但是一直报错,看了其他人的答案,使用的是charAt[0] - ‘0’,就可以了。但是,当行列数大于9的话,不就有问题了吗?可是牛客网又能编译通过,奇怪。
本文介绍了一种在已排序的二维矩阵中查找特定数字的方法,利用矩阵的特性从右上角开始搜索,逐步缩小范围,提高了查找效率。
1264

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



