剪枝可以对特殊案例进行处理
public class Q74_Search_a_2D_Matrix {
public static void main(String[] args) {
System.out.println(searchMatrix(new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, 3));
System.out.println(searchMatrix(new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, 13));
System.out.println(searchMatrix(new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, 8));
}
public static boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length, column = matrix[0].length;
//剪枝,小于最小值,大于最大值
if (target < matrix[0][0] || target > matrix[row - 1][column - 1]) {
return false;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (matrix[i][j] == target) {
return true;
}
if (j == column - 1) { //一行的最后一个元素和下一行的第一个元素之间的取值范围和target大小的判断
if (target > matrix[i][j] && target < matrix[i + 1][0]) {
return false;
}
} else {
if (target > matrix[i][j] && target < matrix[i][j + 1]) {
return false;
}
}
}
}
return false;
}
}
欢迎讨论