题三:二维数组查找

xiaoxiao2021-02-27  462

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 /* * 方法:从右上角开始查询,比右上角的数字大,则该行排除,比右上角的数字小,则该列排除 */ public class test3 { public static boolean Find(int target, int [][] array) { int length = array.length;

int x =0; int y = array[0].length-1; //数字如果为null,返回false if(array==null){ return false; } while (x<length&&y>=0) { //等于右上角的数字时返回false if(array[x][y]==target){ return true; }else if(target>array[x][y]){ //排除第x行 x++; continue; }else{ //排除第y列 y--; continue; } } //没找到返回false return false;

} public static void main(String[] args){ int[][] x = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}}; System.out.println(Find(6, x)); } }

转载请注明原文地址: https://www.6miu.com/read-1092.html

最新回复(0)