题目
思路
- 暴力解法,直接遍历矩阵,时间复杂度为o(n^2),空间复杂度为o(1).
- 遍历每一行,对每一行进行二分查找,时间复杂度为o(nlogn),空间复杂度为o(1)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size();
for( int i = 0; i < row; i++) {
bool res = binary(matrix[i],target);
if(res == true) {
return true;
}
}
return false;
}
public:
bool binary(vector<int>& nums,int target) {//二分查找
int low = 0;
int high = nums.size()-1;
int mid = (low+high)/2;
while(low<=high) {
int mid = (low+high)/2;
if( nums[mid] == target ) {
return true;
}else if(target > nums[mid] ) {
low = mid+1;
}
else {
high = mid-1;
}
}
return false;
}
};
进阶
我们知道矩阵右上角的元素是该行的最小元素,该列的最大元素,因此可以从右上角开始遍历,当目标值大于当前值时,向下遍历,当目标值小于当前值时,向左遍历。向下遍历的次数最多为行数,向左遍历的次数最多为列数,故时间复杂度为o(n+m)(n和m是行数和列数),空间复杂度为o(1)。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size();
int col = matrix[0].size();
int i = row-1;
int j = 0;
while( i >= 0 && j <col) {
if(matrix[i][j] == target) {
return true;
} else if( matrix[i][j] <target ) {
j++;
} else {
i--;
}
}
return false;
}
};