Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following 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] ]
Given target = 5
, return true
.
Given target = 20
, return false
.
1.分治法(TLE了)O(mn)。从左上角出发。利用好如果这个点都不是target了,那目标肯定不会出现在右下角这个性质及时停止搜索止损。如果当前点大了,那肯定没希望了;如果当前点就是目标,那已经成功了;如果当前点小了,分治,向右或者向下找,拆成两个子问题。因
2.行走法 O(m + n)。从右上角出发。利用好如果当前点大了,这列向下都不可能了,向左走;如果当前点小了,这行向左都不可能了,向下走这个性质。用好性质不一定最差情况要走遍所有格子,走一条路径即可。
实现1:
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return false; } return helper(matrix, target, 0, 0); } private boolean helper(int[][] matrix, int target, int x, int y) { if ( x >= matrix.length || y >= matrix[0].length || matrix[x][y] > target ) { return false; } if (matrix[x][y] == target) { return true; } if (helper(matrix, target, x + 1, y) || helper(matrix, target, x, y + 1)) { return true; } return false; } }
实现2:
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return false; } int x = 0; int y = matrix[0].length - 1; while (isInBound(matrix, x, y) && matrix[x][y] != target) { if (matrix[x][y] > target) { y--; } else { x++; } } if (isInBound(matrix, x, y)) { return true; } return false; } private boolean isInBound(int[][] matrix, int x, int y) { return x >= 0 && x < matrix.length && y >= 0 && y < matrix[0].length; } }