LeetCode_Search a 2D Matrix

时间:2023-03-09 22:02:54
LeetCode_Search a 2D Matrix
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 from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example, Consider the following matrix: [
[, , , ],
[, , , ],
[, , , ]
]
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int m = matrix.size();
int n = matrix[].size();
if(target < matrix[][] || target >matrix[m-][n-])return false; int i,j; for(i = ;i< m-;i++)
if(target >=matrix[i+][])
continue;
else
break ; for(j = ; j< n; j++)
if(target == matrix[i][j])
return true;
else if(target <matrix[i][j])
return false;
}
};

感觉上面的方法虽然过了所有case,但还是可能有问题的,看了《剑指offer》后,才发现了一种更好的解法:

class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int m = matrix.size();
int n = matrix[].size(); int row = , column = n -;
while(row < m && column >= )
{ if(matrix[row][column] == target)
return true;
else if(matrix[row][column] > target)
column--;
else
row++;
}
return false;
}
};