二维数组中查找 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;

}

}

posted @ 2015-03-30 19:32  keedor  阅读(167)  评论(0编辑  收藏  举报