-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2.SearchInA2DMatrixI.cpp
More file actions
41 lines (34 loc) · 965 Bytes
/
2.SearchInA2DMatrixI.cpp
File metadata and controls
41 lines (34 loc) · 965 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
#include <bits/stdc++.h>
using namespace std;
bool searchMatrix(const vector<vector<int>>& matrix, int target) {
int n = matrix.size();
if (n == 0) return false;
int m = matrix[0].size();
if (m == 0) return false;
int low = 0, high = n * m - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int row = mid / m;
int col = mid % m;
int val = matrix[row][col];
if (val == target)
return true;
else if (val < target)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, target;
cin >> n >> m >> target;
vector<vector<int>> matrix(n, vector<int>(m));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> matrix[i][j];
cout << (searchMatrix(matrix, target) ? "true" : "false") << "\n";
return 0;
}