Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.
This matrix has the following properties:
- Integers in each row are sorted from left to right.
- Integers in each column are sorted from up to bottom.
- No duplicate integers in each row or column.
Example
分析:搜索每一行,每一行第一个值小于target并且最后一个大于target,则搜索这一行. 但是复杂度略高.
Consider the following matrix:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
public class Solution {
/**
* @param matrix: A list of lists of integers
* @param: A number you want to search in the matrix
* @return: An integer indicate the occurrence of target in the given matrix
*/
public int searchMatrix(int[][] matrix, int target) {
int res = 0;
if(matrix.length == 0) return 0;
for(int i = 0; i < matrix.length; i++) {
if(matrix[0].length == 0) return 0;
if(matrix[i][0] <= target && matrix[i][matrix[0].length - 1] >= target) {
for(int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == target) res ++;
}
}
}
return res;
}
}
为了提高搜索效率,可以考虑使用杨氏矩阵的搜索. 从左下开始.
public class Solution {
/**
* @param matrix: A list of lists of integers
* @param: A number you want to search in the matrix
* @return: An integer indicate the occurrence of target in the given matrix
*/
public int searchMatrix(int[][] matrix, int target) {
int res = 0;
if(matrix.length == 0) return 0;
if(matrix[0].length == 0) return 0;
//从左下角开始搜索 当判断比target大或者比target小时 只有一种情况
int row = matrix.length - 1, col = 0;
while(row >= 0 && col <= matrix[0].length - 1) {
if(target == matrix[row][col]) {
res++;
row--;
col++;
} else if (target < matrix[row][col]){
row--;
} else {
col++;
}
}
return res;
}
}