38. 搜索二维矩阵 II
2018-03-06 21:14
441 查看
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
样例考虑下列矩阵:[ [1, 3, 5, 7], [2, 4, 7, 8], [3, 5, 9, 10]]给出target = 3,返回 2public 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 || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return 0;
int row = matrix.length - 1;
int col = matrix[0].length - 1;
int x = row;
int y = 0;
int res = 0;
while(x >= 0 && y <= col){
if(matrix[x][y] < target){
y++;
} else if(matrix[x][y] > target){
x--;
} else {
res++;
x--;
y++;
}
}
return res;
}
}
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
样例考虑下列矩阵:[ [1, 3, 5, 7], [2, 4, 7, 8], [3, 5, 9, 10]]给出target = 3,返回 2public 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 || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return 0;
int row = matrix.length - 1;
int col = matrix[0].length - 1;
int x = row;
int y = 0;
int res = 0;
while(x >= 0 && y <= col){
if(matrix[x][y] < target){
y++;
} else if(matrix[x][y] > target){
x--;
} else {
res++;
x--;
y++;
}
}
return res;
}
}
相关文章推荐
- 搜索二维矩阵 II
- 搜索二维矩阵 II
- 搜索二维矩阵 II
- lintcode,搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- LintCode-38.搜索二维矩阵 II
- 38 - 搜索二维矩阵 II
- LintCode 38 搜索二维矩阵 II
- 搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- [Lintcode] Search a 2D Matrix II搜索二维矩阵 II
- [LintCode]38.搜索二维矩阵 II
- 搜索二维矩阵 II
- 搜索二维矩阵 II
- lintcode-搜索二维矩阵II-38
- 搜索二维矩阵 II
- Google/LintCode:M-搜索二维矩阵 II
- [LintCode]搜索二维矩阵 II
- [LeetCode] 240. Search a 2D Matrix II 搜索一个二维矩阵 II
- 搜索二维矩阵 II