编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
示例 1:

输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 输出:true
示例 2:

输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 输出:false
- package TOP11_20;
-
- /**
- *
- * 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
- *
- * 每行的元素从左到右升序排列。
- * 每列的元素从上到下升序排列。
- *
- */
- public class Top19 {
- public static boolean searchMatrix(int[][] matrix, int target) {
- if (matrix.length == 0) {
- return false;
- }
-
- int rowLength = matrix.length;
- int colHeight = matrix[0].length;
- int row = 0;
- int col = colHeight - 1;
- // 从矩阵右上角看 右上角值>target 那么就减少列大小,数值再进行对比,右上角值
- while (row < rowLength && col >= 0) {
- if (matrix[row][col] < target) {
- row++;
- } else if (matrix[row][col] > target) {
- col--;
- } else {
- return true;
- }
- }
- return false;
- }
-
- public static void main(String[] args) {
- int[][] nums ={{1,4,7,11,15},{2,5,8,12,19},{3,6,9,16,22},{10,13,14,17,24},{18,21,23,26,30}};
- System.out.println(searchMatrix(nums,20));
- }
- }