这种矩阵的特点是:
1、最右边的元素是其所在行中最大的元素,是其所在列中最小的元素
2、最左边元素是一行中最小的元素,是其所在列中最大的元素。
zh
bool searchMatrix(int*matrix, int rows, int cols, int target){
bool found = false;
int row = 0;
int col = cols-1;
if(matrix == NULL) return;
while(row < rows && col >= 0){
if(matrix[cols*row + col] == target){
found = true;
break;
}
//matrix[cols*row + col]最右边的点是一行中最大的数,一列中最小的数
//矩阵最右边的点 > 目标
if( matrix[cols*row + col] > target){
//列最小的数都比目标大,那么这一列就可以舍弃了
col--;
}else
//一行中最大的值小于目标的话,
//那么这一行肯定不包含target了,这行就可以不考虑了
row++;
}
return found;
}
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.empty())
return false;
int rows = matrix.size();
int columns = matrix[0].size();
int row = 0;
int column = columns -1;
bool found = false;
while(row < rows && column >= 0){
if(matrix[row][column] > target)
column--;
else if (matrix[row][column] < target)
row++;
else{
found = true;
break;
}
}
return found;
}