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.
我的做法,很直观。复杂度是O(m*n)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row_sum = matrix.size();
if (row_sum == 0) return false;
int column_sum = matrix[0].size();
if (column_sum == 0) return false;
for (int i = 0; i < row_sum; i++) {
if (matrix[i][0] > target) break;
for (int j = 0; j < column_sum; j++) {
if (matrix[i][j] == target) return true;
else if (matrix[i][j] > target) break;
}
}
return false;
}
};
discussion中的方法,复杂度O(m+n)
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if (m == 0) return false;
int n = matrix[0].size();
int i = 0, j = n - 1;
while (i < m && j >= 0) {
// 如果是{{}}类型的矩阵,或者说行向量是{}.
// 如果n==0,n - 1 的值就是-1,自动结束循环
if (matrix[i][j] == target)
return true;
else if (matrix[i][j] > target) {
j--;
} else // matrix[i][j] < target
i++;
}
return false;
}
从右上角开始,一行一行地进行搜索,如果这一行的最后一个数小于target,那就移到下一行;矩阵删去第一行,剩下一个子矩阵继续重复上述操作。
否则如果这一行的最后一个数大于target,则这一列的数都会大于target,删去最后一列,剩下一个子矩阵重复上述操作。