二维数组中查找 3

先判断数组是否为空,为空返回false

   

不为空进入循环

   

获得矩阵的行数:rows=matrix.length

获得矩阵的列数:columns=matrix[0].length

   

从最右上角开始找,初始化rowcolumn:row=0,column=columns-1;

   

所以while条件为 row<rows&&column>=0

   

如果找到,即matrix[row][column]=number,并将found置为true

   

如果没找到,当前数大于Number,在左边找,column–

   

当前数小于Number,在右边找,row++

   

package findInMatrix;

   

public class FindInMatrix {

   

public static void main(String[] args) {

// TODO Auto-generated method stub

test1();

test2();

}

   

static void test1() {

int matrix[][] = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 },

{ 6, 8, 11, 15 } };

System.out.println(find(matrix, 1));

}

   

static void test2() {

System.out.println(find(null, 7));

}

   

static boolean find(int[][] matrix, int number) {

   

boolean found = false;

   

if (matrix != null) {

   

int rows = matrix.length;

int columns = matrix[0].length;

int row = 0;

int column = columns – 1;

   

while (row < rows && column >= 0) {

if (matrix[row][column] == number) {

found = true;

break;

} else if (matrix[row][column] > number) {

–column;

} else {

++row;

}

}

}

return found;

}

}

    原文作者:keedor
    原文地址: https://www.cnblogs.com/keedor/p/4378945.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞