1、题目
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.
[ [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
.
2、解题思路
题目里提到高效算法,我首先想到的是二分查找,一行一行地进行同样的二分查找(分治思想),但是有点偷懒了,直接用了c++库里的binary_search,本来以为答案会超出时间限制,但是AC了。。。
3、代码如下
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0)
return false;
int i = 0;
while (i < matrix.size() && !binary_search(matrix[i].begin(), matrix[i].end(), target))
i++;
if (i < matrix.size() - 1)
return true;
else
return binary_search(matrix[matrix.size() - 1].begin(), matrix[matrix.size() - 1].end(), target);
}
};
4、一些说明
首先,在本地编译时加入<algorithm>头函数
其次,要考虑到空矩阵的情形:
1.0 matrix整个是空的,也就是
if (matrix.size() == 0)
return false;
2.0 matrix不空,但每一行都是空的
while (i < matrix.size() && !binary_search(matrix[i].begin(), matrix[i].end(), target))
注意,要先检查size,再进入二分搜索,不然很可能有运行时错误(利用到了短路?就是前一个为false,&&的第二个会被跳过)