Skip to content

Commit 750d074

Browse files
committed
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
1 parent f0163a1 commit 750d074

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.algorithm.study.demo.algorithm;
2+
3+
/**
4+
* 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
5+
* 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
6+
* <p/>
7+
* 规律:首先选取数组中右上角的数字。如果该数字等于要查找的数字,查找过程结束:
8+
* 如果该数字大于要查找的数字,剔除这个数字所在的列:如果该数字小于要查找的数字,剔除这个数字所在的行。
9+
* 也就是说如果要查找的数字不在数组的右上角,则每-次都在数组的查找范围中剔除)行或者一列,这样每一步都可以缩小
10+
**/
11+
12+
public class Jianzhi01 {
13+
14+
public static boolean find(int[][] matrix, int number) {
15+
16+
if (matrix==null || matrix.length<1 || matrix[0].length<1){
17+
return false;
18+
}
19+
20+
int rows=matrix.length;//数组的行数
21+
int cols=matrix[0].length;//数组的列数
22+
23+
int row=0;//从第1行开始读取
24+
int col=cols-1;//从第1列开始
25+
26+
while (row>=0 && row<rows && col>=0){
27+
if (matrix[row][col]==number){
28+
return true;
29+
}else if(matrix[row][col]>number){
30+
col--;//从右往左边开始读取
31+
}else{
32+
row++;//读取下一行
33+
}
34+
}
35+
return false;
36+
37+
38+
}
39+
public static void main(String[] args) {
40+
int[][] matrix = {
41+
{1, 2, 8, 9},
42+
{2, 4, 9, 12},
43+
{4, 7, 10, 13},
44+
{6, 8, 11, 15}
45+
};
46+
System.out.println(find(matrix, 15)); // 要查找的数在数组中
47+
}
48+
}

0 commit comments

Comments
 (0)