Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ]
Given target = 5
, return true
.
Given target = 20
, return false
.
给定的二维数组中,每行每列都是已经排好序的,我们可以先拿每行的最后一个元素与目标比较,如果比目标小,则可以排除此行,然后再拿每列的最后一个元素与目标比较,如果比目标小,则可以排除此列,用这样的方法可以缩小查找的范围,最后我们在缩小的范围内进行线性搜索。源代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m=matrix.size(),n=matrix[0].size();
int i=0,j=0;
for(;i<m;i++)
if(matrix[i][n-1]>=target) break;
for(;j<n;j++)
if(matrix[m-1][j]>=target) break;
for(int k=i;k<m;k++)
for(int l=j;j<n;l++)
{
if(matrix[k][l]==target) return true;
if(matrix[k][l]>target) break;
}
return false;
}
};
这个算法效率也不算太高,在最坏的情况下复杂度也会达到O(mn)