题目:
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
.
本题可以用二分法来解。注意到将这个数组从第一行第一个从0开始编号,下一行的第一个接上一行的最后一个,最后一个的序号为n1*n2-1;
那么每个元素按照我们编号的顺序是严格递增的。
所以我们可以对index从0-n1*n2-1用二分法来做,唯一要解决的是将index还原到数组中对应的行号和列号。当然这非常容易;
时间复杂度:O(lg(n1*n2))
实现如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int size1 = matrix.size();
if (size1 < 1) return false;
int size2 = matrix[0].size(),n=size1*size2;
if (size2 == 0) n = size1;
int left = 0, right = n - 1,index=n/2;
while (left <= index && index <= right)
{
int row = index / size2, column = index%size2;
if (matrix[row][column] == target) return true;
if (matrix[row][column] > target)
{
right = index - 1;
index -= (index - left + 1) / 2;
}
else
{
left = index + 1;
index += (right - index + 1) / 2;
}
}
return false;
}
};