题目描述
判断一个数是否存在顺序矩阵(矩阵从左到右,从上到下,依次变大)中,如果存在,返回ture,否则,返回flase;

解题思路
先从右上角的节点开始,传入的数如果大于该节点则行加一,如果小于则列减一,循环此过程,循环条件是
row < matrix.length && col > -1 行不超过最大行,列不小于最小列。
代码实现
package class_03;
public class Code_09_FindNumInSortedMatrix {
public static boolean isContains(int[][] matrix, int K) {
int row = 0; //行
int col = matrix[0].length - 1; //获取列
//matrix.length 获取行
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[][] matrix = new int[][] {
{ 0, 1, 2, 3, 4, 5, 6 },// 0
{ 10, 12, 13, 15, 16, 17, 18 },// 1
{ 23, 24, 25, 26, 27, 28, 29 },// 2
{ 44, 45, 46, 47, 48, 49, 50 },// 3
{ 65, 66, 67, 68, 69, 70, 71 },// 4
{ 96, 97, 98, 99, 100, 111, 122 },// 5
{ 166, 176, 186, 187, 190, 195, 200 },// 6
{ 233, 243, 321, 341, 356, 370, 380 } // 7
};
int K = 233;
System.out.println(isContains(matrix, K));
}
}
网友评论