File tree 1 file changed +29
-1
lines changed
algorithms/cpp/search2DMatrix
1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change 26
26
27
27
class Solution {
28
28
public:
29
- bool searchMatrix (vector<vector<int > > &matrix, int target) {
29
+ bool searchMatrix (vector<vector<int >>& matrix, int target) {
30
+ return searchMatrix01 (matrix, target);
31
+ return searchMatrix02 (matrix, target);
32
+ }
33
+
34
+ // Just simply convert the 2D matrix to 1D array.
35
+ bool searchMatrix01 (vector<vector<int >>& matrix, int target) {
36
+ int row = matrix.size ();
37
+ int col = row>0 ? matrix[0 ].size () : 0 ;
38
+
39
+ int len = row * col;
40
+ int low = 0 , high = len -1 ;
41
+ while (low <= high) {
42
+
43
+ int mid = low + (high - low) / 2 ;
44
+ int r = mid / col;
45
+ int c = mid % col;
46
+
47
+ int n = matrix[r][c];
48
+ if (n == target) return true ;
49
+ if (n < target) low = mid+1 ;
50
+ else high = mid -1 ;
51
+ }
52
+ return false ;
53
+ }
54
+
55
+
56
+
57
+ bool searchMatrix02 (vector<vector<int > > &matrix, int target) {
30
58
31
59
int idx = vertical_binary_search (matrix, target);
32
60
if (idx<0 ){
You can’t perform that action at this time.
0 commit comments