【题目】 给定一个有N*M的整型矩阵matrix和一个整数K, matrix的每一行和每一 列都是排好序的。实现一个函数,判断K 是否在matrix中。
例如:
0 1 2 5
2 3 4 7
4 4 4 8
5 7 7 9
如果K为7,返回true;如果K为6,返 回false。
【要求】 时间复杂度为O(N+M),额外空间复杂度为O(1)
思路:
注意题目要求,整个矩阵的的每一行和每一 列都是排好序的,因此我们可以从矩阵的右上角(a,b)开始遍历,当要查找的数K大于(a,b)时,则往下遍历(a+1,b);反之则往右遍历(a,b-1);这样最多遍历M+N次就找到了。
代码:
package basic_class_03;
import java.util.Scanner;
/**
* 类名:Code_09_FindNumInSortedMatrix<br>
* 功能:在行列都排好序的矩阵中找数
* 【题目】 给定一个有N*M的整型矩阵matrix和一个整数K, matrix的每一行和每一 列都是排好序的。
* 实现一个函数,判断K 是否在matrix中。
* 例如: 0 1 2 5 2 3 4 7 4 4 4 8 5 7 7 9 如果K为7,返回true;如果K为6,返 回false。
* 【要求】 时间复杂度为O(N+M),额外空间复杂度为O(1)。<br>
* 作者:java战士<br>
* 日期:2019/8/25<br>
* 版本:v1.0.0
* 历史修订:
*/
public class Code_09_FindNumInSortedMatrix {
public static boolean isConstains(int[][] matrix,int k){
int row=0;
int col=matrix[0].length-1;
while (row<matrix.length&&col>-1){
if (matrix[row][col]==k){
return true;
}else if (matrix[row][col]>k){
col--;
}else {
row++;
}
}
return false;
}
public static void main(String[] args){
int[][] arr=new int[][]{
{0,1,4,5,7},
{3,4,8,9,11},
{5,6,12,1,4,15},
{6,8,14,101,203},
};
Scanner scanner=new Scanner(System.in);
int k=scanner.nextInt();
System.out.println(isConstains(arr,k));
}
}
测试结果: