问题描述
在一个n*m的二维数组中,每一行都按照从从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。输入一个二维数组和一个整数,判断数组中是否含有该整数。
输入:n表示有n行,m表示m列,输入数组中的所有元素后,输入一个target。
输出:true或false
方法一:从右上角开始查找
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = scanner.nextInt();
}
}
int target = scanner.nextInt();
System.out.println(findNumberIn2DArray(matrix, target));
}
public static boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) return false;
int i = 0;
int j = matrix[0].length-1;
while (i < matrix.length && j >= 0) {
if (target > matrix[i][j]) {
i++;
} else if (target < matrix[i][j]) {
j--;
} else {
return true;
}
}
return false;
}
}
方法二:从左下角开始查找
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = scanner.nextInt();
}
}
int target = scanner.nextInt();
System.out.println(findNumberIn2DArray(matrix, target));
}
public static boolean findNumberIn2DArray(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) return false;
int i = matrix.length - 1;
int j = 0;
while (i >= 0 && j < matrix[0].length) {
if (target > matrix[i][j]) {
j++;
} else if (target < matrix[i][j]) {
i--;
} else {
return true;
}
}
return false;
}
}