二维数组查找是否存在数字
import java.util.Scanner;
/**
* 二维数组查找
* 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列按照从上到下递增的顺序排序。
* 写一个函数,输入一个二维数组和一个整数,判断该数组中是否含有这样一个整数
*/
public class search2Darray {
public static boolean search(int[][] arr, int num) {
//判断参数合法性
if (arr == null || arr.length == 0) {
return false;
}
//从右上角开始
int row=0;
int col = arr[0].length - 1;
while (row<=arr.length-1&&col>=0) {
if (num == arr[row][col]) {
return true;
} else if (num > arr[row][col]) {
//往下走 行++
row++;
} else {
//往左走 列--
col--;
}
}
return false;
}
public static void main(String[] args){
int[][] arr={{1,2,8,9},{2,4,10,11},{4,7,12,13},{6,8,15,17}};
System.out.println(search(arr,15));
}
}