题目:
在一个二维数组中,每一行都从左到右,每一列从上到下,都按照递增的顺序排序,请输入一个这样的二维数组和一个整数,判断数组中是否含有该整数。
import java.util.Scanner;
public class FindElement {
private int [] a = new int[100];
public static boolean find(int[] a,int rows , int columns , int number){
boolean found = false;
if(a.length!=0&&rows>0 && columns>0){
//从右上角开始找
int row = 0;
int column = columns-1;
//因为相当于从向左下角移动,会出现行大于数组的行或列小于数组的列的情况。
while(row<rows&&column>=0){
if(a[row*columns+column] == number){
found = true;
break;
}else if(a[row*columns+column]<number){
//如果要找的数字大于当前数组位置上的数字,而且当前位置上的数字一定是
//该行中最大的,所以把这行滤掉
row++;
}else if(a[row*columns+column]>number){
//如果要找的数字小于当前数组位置上的数字,而且当前位置上的数字一定是
//该列中最大的,所以把这列滤掉
column--;
}
}
}
return found;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//输入几行
int rows = scan.nextInt();
//输入几列
int columns = scan.nextInt();
//计算机总共的元素数
int count = rows*columns;
int[] number = new int[count];
for(int i = 0; i < count; i++)
number[i] = scan.nextInt();
boolean result = find(number,rows,columns,27);
System.out.println(result);
}
}
从左下角开始找
import java.util.Scanner;
public class FindElement {
private int [] a = new int[100];
public static boolean find(int[] a,int rows , int columns , int number){
boolean found = false;
if(a.length!=0&&rows>0 && columns>0){
//从左下角开始找
int row = rows-1;
int column = 0;
//因为相当于从向右上角移动,会出现行小于0或列大于数组的列的情况。
while(row>=0&&column<columns){
if(a[row*columns+column] == number){
found = true;
break;
}else if(a[row*columns+column]<number){
//如果要找的数字大于当前数组位置上的数字,而且当前位置上的数字一定是
//该列中最大的,所以把这列滤掉
column++;
}else if(a[row*columns+column]>number){
//如果要找的数字小于当前数组位置上的数字,而且当前位置上的数字一定是
//该行中最小的,所以把这行滤掉
row--;
}
}
}
return found;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//输入几行
int rows = scan.nextInt();
//输入几列
int columns = scan.nextInt();
//计算机总共的元素数
int count = rows*columns;
int[] number = new int[count];
for(int i = 0; i < count; i++)
number[i] = scan.nextInt();
boolean result = find(number,rows,columns,9);
System.out.println(result);
}
}