题目描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
题目解答:
第一种:直接使用暴力求解,即二重循环
第二种:从左下角元素往上查找,右边元素是比这个元素大,上边是的元素比这个元素小。于是,target 比这个元素小就往上找,比这个元素大就往右找。如果出了边界,则说明二维数组中不存在 target 元素。
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
int m = input.nextInt();
int n = input.nextInt();
int[][] a = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = input.nextInt();
}
}
while (input.hasNext()) {
int target = input.nextInt();
System.out.println("Solution1:");
System.out.println(Find1(target, a));
System.out.println("Solution2:");
System.out.println(Find2(target, a));
}
}
input.close();
}
//暴力求解
private static boolean Find1(int target, int[][] array) {
int rows = array.length;
int cols = array[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (array[i][j] > target) {
break;
}
if (array[i][j] == target) {
return true;
}
}
}
return false;
}
//从左下角开始查找,线性求解
private static boolean Find2(int target, int[][] array) {
int rows = array.length;
int cols = array[0].length;
int i = rows - 1, j = 0;
while (i >= 0 && j < cols) {
if (target == array[i][j]) {
return true;
} else if (target < array[i][j]) {
i--;
} else {
j++;
}
}
return false;
}
}
运行结果:
Input:
2 4
1 2 3 6
3 4 5 7
5
0
Output:
Solution1:
true
Solution2:
true
Solution1:
false
Solution2:
false