领扣LintCode问题答案-38.-搜索二维矩阵-II
目录
领扣LintCode问题答案-38. 搜索二维矩阵 II
领扣LintCode问题答案-38. 搜索二维矩阵 II
目录
38. 搜索二维矩阵 II
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
样例 1:
输入:
[[3,4]]
target=3
输出:1
样例 2:
输入:
[
[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 target: An integer you want to search in matrix
* @return: An integer indicate the total occurrence of target in the given matrix
*/
public int searchMatrix(int[][] matrix, int target) {
// write your code here
if (matrix == null) {
return 0;
}
int maxR = matrix.length;
if (maxR == 0) {
return 0;
}
int maxC = matrix[0].length;
if (maxC == 0) {
return 0;
}
int count = 0;
for (int[] row : matrix) {
int index = Arrays.binarySearch(row, target);
if (index >= 0) {
count++;
}
}
return count;
}
}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。