[Description]
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following 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] ]
Given target = 5
, return true
.
Given target = 20
, return false
.
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int size = matrix.size();
if (size == 0) return false;
int x = 0, y = matrix[0].size()-1;
while (y >= 0 && x < size) {
if (matrix[x][y] == target) {
return true;
} else if (matrix[x][y] < target) {
x++;
} else {
y--;
}
}
return false;
}
};
这道题上我花了一些时间,也帮我更好的理解了分治法的思想。
原本我的思路是每一步比较对角线的中点和target的值,这样第一次比较就能减少1/4的区域,之后每次也会减少一部分,但是在结束比较了以后发现target可能出现的区域是两个矩形,随着矩阵规模的增大矩形也会变大。
即图中黄色区域。
这样子在两个矩形里搜索并没有什么改善。
于是我改变方法,从右上角的元素开始对比,若target大于此数字,则该元素所在列均不需要考虑,若target小于此数字,则该元素所在行均不需要考虑。这样在O(m+n)的时间里就可以完成一次对矩阵的搜索,效果不错。