描述:
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
- 每行中的整数从左到右是排序的。
- 每一列的整数从上到下是排序的。
- 在每一行或每一列中没有重复的整数。
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
Java代码:
左上最小,右下最大,右上和左下中位数
offer书上说只能从右上和左下开始搜索,我不同意,矩阵很大的时候,应该根据和四个角的值谁更接近来决定从哪个角开始寻找。
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) {
// write your code here
if(matrix==null ||matrix.length==0){
return 0;
}
int row = matrix.length;
int column = matrix[0].length;
int count = 0;
for(int i=0 ; i<row ; i++){
for(int j=0 ;j < column;j++){
if(target==matrix[i][j]){
count++;
column = j;
break;
}
if(matrix[i][j]>target){
column = j;
break;
}
}
}
return count;
}
}