寫出一個高效的算法來搜索m×n矩陣中的值,返回這個值出現的次數。
這個矩陣具有以下特性:
- 每行中的整數從左到右是排序的。
- 每一列的整數從上到下是排序的。
- 在每一行或每一列中沒有重複的整數。
樣例
考慮下列矩陣:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
給出target = 3,返回 2
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=column-1;j>=0;j--){
if(matrix[i][j]==target){
column=j;
count++;
break;
}
}
}
return count;
}
}