-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy path74_Search2DMatrix.cpp
More file actions
41 lines (39 loc) · 925 Bytes
/
74_Search2DMatrix.cpp
File metadata and controls
41 lines (39 loc) · 925 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
39
40
41
/*
* @Author: xuezaigds@gmail.com
* @Last Modified time: 2016-04-13 11:17:48
*/
class Solution {
public:
// Don't treat it as a 2D matrix, just treat it as a sorted list
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty()){
return false;
}
int m_rows = matrix.size(), n_cols = matrix[0].size();
int left=0, right = m_rows*n_cols-1;
while(left <= right){
int mid = left + (right-left) / 2;
int num = matrix[mid/n_cols][mid%n_cols];
if(num < target){
left = mid + 1;
}
else if(num > target){
right = mid - 1;
}
else{
return true;
}
}
return false;
}
};
/*
[[]]
0
[[1]]
0
[[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
34
[[1, 3, 5], [10, 11, 16], [23, 30, 34]]
46
*/