LintCode 38 搜索二维矩阵 II
2017-04-23 22:40
351 查看
题目:searchMatrix
要求:
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
样例:
考虑下列矩阵:[
[1, 3, 5, 7], [2, 4, 7, 8], [3, 5, 9, 10]
]
给出target = 3,返回 2
算法要求:
要求O(m+n) 时间复杂度和O(1) 额外空间解题思路:
根据题中给出的排序状态,就可以进行躲避无用的搜索操作啦。算法如下:
int searchMatrix(vector<vector<int> > &matrix, int target) { // write your code here int num = 0; int size2 = matrix.size(); if (size2 == 0) { return 0; } int size = matrix[0].size(); for (int i = 0; i < size && matrix[0][i] <= target; i++) { for (int j = 0; j < size2 && matrix[j][i] <= target; j++) { if (matrix[j][i] == target) { num++; } } } return num; }
相关文章推荐
- LintCode-38.搜索二维矩阵 II
- [LintCode]38.搜索二维矩阵 II
- lintcode-搜索二维矩阵II-38
- 38 - 搜索二维矩阵 II
- lintcode,搜索二维矩阵 II
- 【LintCode】搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- LintCode之38 搜索二维矩阵 II
- [Lintcode] Search a 2D Matrix II搜索二维矩阵 II
- lintcode. 28 搜索二维矩阵
- 搜索二维矩阵 II
- 搜索二维矩阵 II
- LintCode:搜索二维矩阵 II
- 搜索二维矩阵 II
- Google/LintCode:M-搜索二维矩阵 II
- 搜索二维矩阵——LintCode
- 搜索二维矩阵 II
- [LintCode]28.搜索二维矩阵
- (lintcode)第28题 搜索二维矩阵
- lintcode ---- 搜索二维矩阵