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.
start from right top:
1. target less than the number, col--;(exclude this column)
2. target larger than the number, row++;(exclude this row)
3. target equals the number
class Solution { public boolean searchMatrix(int[][] matrix, int target) { int a=matrix.length; if(a==0) return false; int b=matrix[0].length; if(b==0) return false; int col=b-1; int row=0; while(col>=0&&row<a){ if(target==matrix[row][col]) return true; else if(target<matrix[row][col]) col--; else row++; } return false; } }
需要找到一个点,在这个点上和target比较就可以为一确定的知道该往哪个方向继续搜索,左上角和右下角都不行,右上角和左下角都可以。
注意:不要忘了matrix为空 matrix.length==0 or matrix[0].length==0 的corner case!!
浙公网安备 33010602011771号