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 from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
简单写了三个解法:
解法一、一个一个的遍历二维数组。Accepted! too yaung too naive!
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int m=matrix.size();
int n=matrix[0].size();
// 按行遍历二维数组 ,效率比较高
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(matrix[i][j]==target)
{
return true;
}
}
}
return false;
}
解法二、先看每行最后一个数字,确定是不是在这一行
int row=0;
int col=matrix[row].size()-1;
for(;row<matrix.size() && col>=0;)
{
if(matrix[row][col]==target)
{
return true;
}
else if(matrix[row][col]<target)
{
row++;
}
else
{
col--;
}
}
return false;
}
解法三、因为已经排序,所以就用二分查找,把二位数组当成一位数组看待
int m=matrix.size();
int n=matrix[0].size();
int begin=0;
int end=m*n-1;
while(begin<=end)
{
int middle=(end+begin)/2;
if(matrix[middle/n][middle%n]==target)
{
return true;
}
else if(matrix[middle/n][middle%n]<target)
{
begin=(middle/n)*n+(middle%n)+1;
}
else
{
end=(middle/n)*n+(middle%n)-1;
}
}
return false;
}