Skip to content

Commit 9dd87d4

Browse files
committed
simpler solution
1 parent ccadca1 commit 9dd87d4

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

‎algorithms/cpp/search2DMatrix/search2DMatrix.cpp

+29-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,35 @@
2626

2727
class Solution {
2828
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) {
3058

3159
int idx = vertical_binary_search(matrix, target);
3260
if (idx<0){

0 commit comments

Comments
 (0)