在一个二维数组中,每一行都按照从左到右递增的顺序排序,诶一列都按照从上到下递增的顺序排序,请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否包含了该整数。 |
例如下面的二维数组就是每行、没列都递增排序。如果在这个数组中查找数字7,则返回true(找得到);如果查找数字5,由于数组不含该数字,则返回false。
1 | 2 | 8 | 9 |
2 | 4 | 9 | 12 |
4 | 7 | 10 | 13 |
6 | 8 | 11 | 15 |
解决思路 * 从右上角开始查 * 如果当前数小于需要查询数字A,那么删除这一列 * 如果当前数大于需要查询数字A,那么删除这一行 public class MatrixSearch { /** * 从右上角开始查 * 如果当前数小于需要查询数字A,那么删除这一列 * 如果当前数大于需要查询数字A,那么删除这一行 * @param num 被查找的二维数组 * @param rows 行数 * @param columns 列数 * @param number 要查找的数字 * @return 是否找到要查找的数字(number) */ public boolean find(int num[][],int number) { int rows = num.length; int columns = num[0].length; Boolean found = false; int row = 0; int column = columns - 1 ; if( rows > 0 && columns >0) { while(row < rows && column >= 0) { if(num[row][column] == number) //查找到 { found = true; break; } else if(num[row][column] >number) { --column; //删除列 } else { ++row; //删除行 } } } return found; } public static void main(String[] args) { MatrixSearch matrixSearch = new MatrixSearch(); int[][] matrix = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}}; boolean isIn = matrixSearch.find(matrix, 10); System.out.println(isIn); } }