week18-leetcode #240-Search a 2D Matrix II
链接:https://leetcode.com/problems/search-a-2d-matrix-ii/description/
Question
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.
Solution[1]
复杂度:O(m*n)
class Solution {
public:
// 是否已经找到
bool flag = false;
bool searchMatrix(vector<vector<int> >& matrix, int target) {
int row_size = matrix.size();
if (row_size == 0) return false;
int col_size = matrix[0].size();
return isFindTarget(matrix, target, 0, row_size-1, 0, col_size-1);
}
bool isFindTarget(vector<vector<int> >& matrix, int target, int row_start, int row_end, int col_start, int col_end) {
if (this->flag == true) return true;
if (row_start > row_end || col_start > col_end) return false;
if (row_start == row_end && col_start == col_end) {
if (matrix[row_start][col_start] == target) {
this->flag = true;
return true;
} else {
return false;
}
}
int row_mid = (row_end+row_start)/2;
int col_mid = (col_start+col_end)/2;
return isFindTarget(matrix, target, row_start, row_mid, col_start, col_mid)
|| isFindTarget(matrix, target, row_start, row_mid, col_mid+1, col_end)
|| isFindTarget(matrix, target, row_mid+1, row_end, col_start, col_mid)
|| isFindTarget(matrix, target, row_mid+1, row_end, col_mid+1, col_end);
}
};
思路:最直观的方法,采用分而治之递归的方法,每次将大矩阵分成四个小矩阵,并且不断递归下去,最basic的退出条件是只剩下一个元素的时候。就是后来想了一下,这种方法其实和遍历一遍矩阵没有什么区别,复杂度达到了O(m*n)。
Solution[2]
复杂度:O(m+n)
class Solution {
public:
bool searchMatrix(vector<vector<int> >& matrix, int target) {
int row_size = matrix.size();
if (row_size == 0) return 0;
int col_size = matrix[0].size();
int row_index = row_size-1;
int col_index = 0;
while (row_index >= 0 && col_index < col_size) {
if (matrix[row_index][col_index] == target) {
return true;
} else if (matrix[row_index][col_index] < target) {
col_index++;
} else {
row_index--;
}
}
return false;
}
};
思路:这种方法很机智,主要的想法利用了这个矩阵从左到右逐渐递增,从上往下也是逐渐递增。就是从最左下角的数据出发,如果target大于该数据,则col++;如果target小于该数据,则row–。如果target存在于矩阵中,必然会在往上往右的时候到达。