编写一个高效的算法来搜索 m x n
矩阵 matrix
中的一个目标值 target
。该矩阵具有以下特性:
示例 1:
输入: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]], target = 5 输出:true
示例 2:
输入: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]], target = 20 输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
-109 <= target <= 109
//按行二分查找,行不变,返回对应列下标
int findRow(vector
{
if(matrix[row][0]>target)
{
return -1;
}
//int m=matrix.size();
int n=matrix[0].size();
int left=0;
int right=n-1;
int mid=(left+right)/2;
while(left<=right)
{
mid=(left+right)/2;
if(target==matrix[row][mid])
{
return mid;
}
if(target > matrix[row][mid])
{
left=mid+1;
}
else
{
right=mid-1;
}
}
return -1;
}
int findCol(vector
{
if(matrix[0][col]>target)
{
return -1;
}
int m=matrix.size();
//int n=matrix[0].size();
int left=0;
int right=m-1;
int mid=(left+right)/2;
while(left<=right)
{
mid=(left+right)/2;
if(target==matrix[mid][col])
{
return mid;
}
if(target > matrix[mid][col])
{
left=mid+1;
}
else
{
right=mid-1;
}
}
return -1;
}
bool searchMatrix(vector
if(matrix[0][0]>target)
{
return false;
}
int m=matrix.size();
int n=matrix[0].size();
if(findRow(matrix,0,target)!= -1)
{
return true;
}
for(int i=0;i { if(findCol(matrix,i,target)!= -1) { return true; } } return false; }