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.
思路:这是一个非常典型的二分查找法的应用场景,只不过是把一维数组扩展成了二维数组,因此,解题的关键是将二维数组“转换”为一维数组。代码如下:
int searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { int begin = 0, end = matrixColSize * matrixRowSize - 1; int mid; int row, col; while(begin <= end) { mid = begin+(end-begin)/2; row = mid/matrixColSize; col = mid%matrixColSize; if(matrix[row][col] == target) return 1; if(matrix[row][col] < target) begin = mid+1; else end = mid-1; } return 0; }