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.
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
.
分析
这个题目其实使用暴力搜索的办法估摸着应该不是出题者的本意,遍历行或者列在每行或者每列中做二分查找时间复杂度为m * logn 或者n * logm。
我也是看到了网上别人的很巧妙的解法,其实可以从二维数组的左下角开始寻找,如果matrix[i][j]大于target,那么可以断定[0,i][0,j]的范围([i][j]的左上角)内一定没有target,因为这个范围的数都是比他小的。那么就向右寻找target,即j ++。如果matrix[i][j] > target,那么说明[i][j]的右下角一定没有target,就向上寻找,即i--。
Code
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size();
if (row == 0)
return false;
int col = matrix[0].size();
int i = row - 1;
int j = 0;
while (i >= 0 && j < col)
{
if (matrix[i][j] == target)
return true;
if (matrix[i][j] > target)
{
i --;
}
else if (matrix[i][j] < target)
{
j ++;
}
}
return false;
}
};
运行效率
Runtime: 92 ms, faster than 35.38% of C++ online submissions for Search a 2D Matrix II.
Memory Usage: 13 MB, less than 5.28% of C++ online submissions for Search a 2D Matrix II.