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,&&的第二個會被跳過)