文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- O(mlogn)
1 | class Solution { |
O(m+n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
if(rows == 0) {
return false;
}
int columns = matrix[0].size();
if(columns == 0) {
return false;
}
int top = 0;
int right = columns - 1;
while(top < rows && right >= 0) {
if(target == matrix[top][right]) {
return true;
}
else if(target > matrix[top][right]) {
top++;
}
else {
right--;
}
}
return false;
}
};or
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
if(rows == 0) {
return false;
}
int columns = matrix[0].size();
if(columns == 0) {
return false;
}
int left = 0;
int bottom = rows - 1;
while(left < columns && bottom >= 0) {
if(target == matrix[bottom][left]) {
return true;
}
else if(target > matrix[bottom][left]) {
left++;
}
else {
bottom--;
}
}
return false;
}
};