Search a 2D Matrix
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] ]
Given target = 3
, return true
.
每行都是递增的。
每行的第一个值比上一行最后一个值大。
例如:
考虑下面的矩阵:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
给定 target = 3,返回 false。
分析:
采用二分查找。
难点在于对于 mid 求出其在矩阵中对应的行和列。
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {
int low = 0, high = matrixRowSize * matrixColSize - 1;
int mid = 0, midRow = 0, midCol = 0;
if(!matrix || (matrixRowSize * matrixColSize == 0))/*空指针或空矩阵*/
{
return false;
}
/***二分查找***/
while(low <= high)
{
mid = (low + high)/2;
midRow = mid / matrixColSize; /*属于所在行*/
midCol = mid - midRow * matrixColSize; /*属于所在列*/
if(matrix[midRow][midCol] == target)
{
return true;
}
else if(matrix[midRow][midCol] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return false;
}