-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHomeWork04_Search_a_2D_matrix.cpp
More file actions
38 lines (35 loc) · 995 Bytes
/
HomeWork04_Search_a_2D_matrix.cpp
File metadata and controls
38 lines (35 loc) · 995 Bytes
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
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int ans_row = 0;
int m = matrix.size();
int n = matrix[0].size();
int left = 0;
int right = m - 1;
while(left < right){
int mid = (left + right + 1)/2;
if(matrix[mid][0] <= target){
left = mid;
}
else{
right = mid - 1;
}
}
if(target < matrix[right][0] || target > matrix[right][n-1]) return false;
ans_row = right;
left = 0;
right = n;
while(left < right){
int mid = (left + right)/2;
if(matrix[ans_row][mid] >= target){
right = mid;
}
else{
left = mid + 1;
}
}
if(matrix[ans_row][right] == target) return true;
//cout << right;
return false;
}
};